dbus-sysdeps.c 84.8 KB
Newer Older
1 2 3
/* -*- mode: C; c-file-style: "gnu" -*- */
/* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
 * 
4
 * Copyright (C) 2002, 2003  Red Hat, Inc.
5
 * Copyright (C) 2003 CodeFactory AB
6
 *
7
 * Licensed under the Academic Free License version 2.1
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * 
 * 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
 *
 */

25
#include "dbus-internals.h"
26
#include "dbus-sysdeps.h"
27
#include "dbus-threads.h"
28
#include "dbus-protocol.h"
29
#include "dbus-test.h"
30
#include <sys/types.h>
31 32
#include <stdlib.h>
#include <string.h>
33
#include <signal.h>
34 35 36
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
37 38
#include <fcntl.h>
#include <sys/socket.h>
39
#include <dirent.h>
40
#include <sys/un.h>
41
#include <pwd.h>
42
#include <time.h>
43
#include <locale.h>
44
#include <sys/time.h>
45
#include <sys/stat.h>
46
#include <sys/wait.h>
47 48
#include <netinet/in.h>
#include <netdb.h>
49
#include <grp.h>
50

51 52 53
#ifdef HAVE_WRITEV
#include <sys/uio.h>
#endif
54 55 56
#ifdef HAVE_POLL
#include <sys/poll.h>
#endif
57 58 59 60
#ifdef HAVE_BACKTRACE
#include <execinfo.h>
#endif

61

62 63 64 65
#ifndef O_BINARY
#define O_BINARY 0
#endif

66 67 68 69
#ifndef HAVE_SOCKLEN_T
#define socklen_t int
#endif

70 71 72 73 74 75 76 77 78 79
/**
 * @addtogroup DBusInternalsUtils
 * @{
 */
/**
 * Aborts the program with SIGABRT (dumping core).
 */
void
_dbus_abort (void)
{
80 81 82 83 84 85
#ifdef DBUS_ENABLE_VERBOSE_MODE
  const char *s;
  s = _dbus_getenv ("DBUS_PRINT_BACKTRACE");
  if (s && *s)
    _dbus_print_backtrace ();
#endif
86 87 88 89
  abort ();
  _exit (1); /* in case someone manages to ignore SIGABRT */
}

90
/**
91 92 93 94 95
 * Wrapper for setenv(). If the value is #NULL, unsets
 * the environment variable.
 *
 * @todo if someone can verify it's safe, we could avoid the
 * memleak when doing an unset.
96 97 98 99 100 101
 *
 * @param varname name of environment variable
 * @param value value of environment variable
 * @returns #TRUE on success.
 */
dbus_bool_t
102 103
_dbus_setenv (const char *varname,
              const char *value)
104
{
105 106 107 108 109 110 111
  _dbus_assert (varname != NULL);
  
  if (value == NULL)
    {
#ifdef HAVE_UNSETENV
      unsetenv (varname);
      return TRUE;
112
#else
113 114
      char *putenv_value;
      size_t len;
115

116
      len = strlen (varname);
117

118 119 120 121 122 123 124 125 126 127 128 129
      /* Use system malloc to avoid memleaks that dbus_malloc
       * will get upset about.
       */
      
      putenv_value = malloc (len + 1);
      if (putenv_value == NULL)
        return FALSE;

      strcpy (putenv_value, varname);
      
      return (putenv (putenv_value) == 0);
#endif
130
    }
131 132 133 134 135 136 137 138 139
  else
    {
#ifdef HAVE_SETENV
      return (setenv (varname, value, TRUE) == 0);
#else
      char *putenv_value;
      size_t len;
      size_t varname_len;
      size_t value_len;
140

141 142 143 144
      varname_len = strlen (varname);
      value_len = strlen (value);
      
      len = varname_len + value_len + 1 /* '=' */ ;
145

146 147 148 149 150 151 152 153 154 155 156 157 158
      /* Use system malloc to avoid memleaks that dbus_malloc
       * will get upset about.
       */
      
      putenv_value = malloc (len + 1);
      if (putenv_value == NULL)
        return FALSE;

      strcpy (putenv_value, varname);
      strcpy (putenv_value + varname_len, "=");
      strcpy (putenv_value + varname_len + 1, value);
      
      return (putenv (putenv_value) == 0);
159
#endif
160
    }
161 162
}

163 164 165 166 167 168 169 170 171 172 173 174
/**
 * Wrapper for getenv().
 *
 * @param varname name of environment variable
 * @returns value of environment variable or #NULL if unset
 */
const char*
_dbus_getenv (const char *varname)
{  
  return getenv (varname);
}

175 176 177 178 179
/**
 * Thin wrapper around the read() system call that appends
 * the data it reads to the DBusString buffer. It appends
 * up to the given count, and returns the same value
 * and same errno as read(). The only exception is that
180 181
 * _dbus_read() handles EINTR for you. _dbus_read() can
 * return ENOMEM, even though regular UNIX read doesn't.
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
 *
 * @param fd the file descriptor to read from
 * @param buffer the buffer to append data to
 * @param count the amount of data to read
 * @returns the number of bytes read or -1
 */
int
_dbus_read (int               fd,
            DBusString       *buffer,
            int               count)
{
  int bytes_read;
  int start;
  char *data;

  _dbus_assert (count >= 0);
  
  start = _dbus_string_get_length (buffer);

  if (!_dbus_string_lengthen (buffer, count))
    {
      errno = ENOMEM;
      return -1;
    }

207
  data = _dbus_string_get_data_len (buffer, start, count);
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227

 again:
  
  bytes_read = read (fd, data, count);

  if (bytes_read < 0)
    {
      if (errno == EINTR)
        goto again;
      else
        {
          /* put length back (note that this doesn't actually realloc anything) */
          _dbus_string_set_length (buffer, start);
          return -1;
        }
    }
  else
    {
      /* put length back (doesn't actually realloc) */
      _dbus_string_set_length (buffer, start + bytes_read);
228 229 230 231 232 233

#if 0
      if (bytes_read > 0)
        _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
#endif
      
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
      return bytes_read;
    }
}

/**
 * Thin wrapper around the write() system call that writes a part of a
 * DBusString and handles EINTR for you.
 * 
 * @param fd the file descriptor to write
 * @param buffer the buffer to write data from
 * @param start the first byte in the buffer to write
 * @param len the number of bytes to try to write
 * @returns the number of bytes written or -1 on error
 */
int
_dbus_write (int               fd,
             const DBusString *buffer,
             int               start,
             int               len)
{
  const char *data;
  int bytes_written;
  
257
  data = _dbus_string_get_const_data_len (buffer, start, len);
258 259 260 261 262
  
 again:

  bytes_written = write (fd, data, len);

263
  if (bytes_written < 0 && errno == EINTR)
264 265
    goto again;

266 267 268 269 270
#if 0
  if (bytes_written > 0)
    _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
#endif
  
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
  return bytes_written;
}

/**
 * Like _dbus_write() but will use writev() if possible
 * to write both buffers in sequence. The return value
 * is the number of bytes written in the first buffer,
 * plus the number written in the second. If the first
 * buffer is written successfully and an error occurs
 * writing the second, the number of bytes in the first
 * is returned (i.e. the error is ignored), on systems that
 * don't have writev. Handles EINTR for you.
 * The second buffer may be #NULL.
 *
 * @param fd the file descriptor
 * @param buffer1 first buffer
 * @param start1 first byte to write in first buffer
 * @param len1 number of bytes to write from first buffer
 * @param buffer2 second buffer, or #NULL
 * @param start2 first byte to write in second buffer
 * @param len2 number of bytes to write in second buffer
 * @returns total bytes written from both buffers, or -1 on error
 */
int
_dbus_write_two (int               fd,
                 const DBusString *buffer1,
                 int               start1,
                 int               len1,
                 const DBusString *buffer2,
                 int               start2,
                 int               len2)
{
  _dbus_assert (buffer1 != NULL);
  _dbus_assert (start1 >= 0);
  _dbus_assert (start2 >= 0);
  _dbus_assert (len1 >= 0);
  _dbus_assert (len2 >= 0);
  
#ifdef HAVE_WRITEV
  {
    struct iovec vectors[2];
    const char *data1;
    const char *data2;
    int bytes_written;

316
    data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
317 318

    if (buffer2 != NULL)
319
      data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
    else
      {
        data2 = NULL;
        start2 = 0;
        len2 = 0;
      }
   
    vectors[0].iov_base = (char*) data1;
    vectors[0].iov_len = len1;
    vectors[1].iov_base = (char*) data2;
    vectors[1].iov_len = len2;

  again:
   
    bytes_written = writev (fd,
                            vectors,
                            data2 ? 2 : 1);

338
    if (bytes_written < 0 && errno == EINTR)
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
      goto again;
   
    return bytes_written;
  }
#else /* HAVE_WRITEV */
  {
    int ret1;
    
    ret1 = _dbus_write (fd, buffer1, start1, len1);
    if (ret1 == len1 && buffer2 != NULL)
      {
        ret2 = _dbus_write (fd, buffer2, start2, len2);
        if (ret2 < 0)
          ret2 = 0; /* we can't report an error as the first write was OK */
       
        return ret1 + ret2;
      }
    else
      return ret1;
  }
#endif /* !HAVE_WRITEV */   
}

362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
#define _DBUS_MAX_SUN_PATH_LENGTH 99

/**
 * @def _DBUS_MAX_SUN_PATH_LENGTH
 *
 * Maximum length of the path to a UNIX domain socket,
 * sockaddr_un::sun_path member. POSIX requires that all systems
 * support at least 100 bytes here, including the nul termination.
 * We use 99 for the max value to allow for the nul.
 *
 * We could probably also do sizeof (addr.sun_path)
 * but this way we are the same on all platforms
 * which is probably a good idea.
 */

377 378 379 380
/**
 * Creates a socket and connects it to the UNIX domain socket at the
 * given path.  The connection fd is returned, and is set up as
 * nonblocking.
381 382 383 384
 * 
 * Uses abstract sockets instead of filesystem-linked sockets if
 * requested (it's possible only on Linux; see "man 7 unix" on Linux).
 * On non-Linux abstract socket usage always fails.
385 386
 *
 * @param path the path to UNIX domain socket
387
 * @param abstract #TRUE to use abstract namespace
388
 * @param error return location for error code
389 390 391 392
 * @returns connection file descriptor or -1 on error
 */
int
_dbus_connect_unix_socket (const char     *path,
393
                           dbus_bool_t     abstract,
394
                           DBusError      *error)
395 396 397
{
  int fd;
  struct sockaddr_un addr;  
398 399

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
400 401 402

  _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
                 path, abstract);
403
  
404
  fd = socket (PF_UNIX, SOCK_STREAM, 0);
405
  
406 407
  if (fd < 0)
    {
408 409 410 411
      dbus_set_error (error,
                      _dbus_error_from_errno (errno),
                      "Failed to create socket: %s",
                      _dbus_strerror (errno)); 
412 413 414 415 416
      
      return -1;
    }

  _DBUS_ZERO (addr);
417
  addr.sun_family = AF_UNIX;
418 419 420 421

  if (abstract)
    {
#ifdef HAVE_ABSTRACT_SOCKETS
422 423 424
      /* remember that abstract names aren't nul-terminated so we rely
       * on sun_path being filled in with zeroes above.
       */
425 426
      addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
      strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
427
      /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
428 429 430 431 432
#else /* HAVE_ABSTRACT_SOCKETS */
      dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
                      "Operating system does not support abstract socket namespace\n");
      close (fd);
      return -1;
433
#endif /* ! HAVE_ABSTRACT_SOCKETS */
434 435 436 437 438
    }
  else
    {
      strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
    }
439 440 441
  
  if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
    {      
442 443 444 445
      dbus_set_error (error,
                      _dbus_error_from_errno (errno),
                      "Failed to connect to socket %s: %s",
                      path, _dbus_strerror (errno));
446 447 448 449 450 451 452

      close (fd);
      fd = -1;
      
      return -1;
    }

453
  if (!_dbus_set_fd_nonblocking (fd, error))
454
    {
455 456
      _DBUS_ASSERT_ERROR_IS_SET (error);
      
457 458 459 460 461 462 463 464 465 466 467 468
      close (fd);
      fd = -1;

      return -1;
    }

  return fd;
}

/**
 * Creates a socket and binds it to the given path,
 * then listens on the socket. The socket is
469 470
 * set to be nonblocking.
 *
471 472 473 474
 * Uses abstract sockets instead of filesystem-linked
 * sockets if requested (it's possible only on Linux;
 * see "man 7 unix" on Linux).
 * On non-Linux abstract socket usage always fails.
475 476
 *
 * @param path the socket name
477
 * @param abstract #TRUE to use abstract namespace
478
 * @param error return location for errors
479 480 481 482
 * @returns the listening file descriptor or -1 on error
 */
int
_dbus_listen_unix_socket (const char     *path,
483
                          dbus_bool_t     abstract,
484
                          DBusError      *error)
485 486 487 488
{
  int listen_fd;
  struct sockaddr_un addr;

489
  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
490 491 492

  _dbus_verbose ("listening on unix socket %s abstract=%d\n",
                 path, abstract);
493
  
494
  listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
495
  
496 497
  if (listen_fd < 0)
    {
498 499 500
      dbus_set_error (error, _dbus_error_from_errno (errno),
                      "Failed to create socket \"%s\": %s",
                      path, _dbus_strerror (errno));
501 502 503 504
      return -1;
    }

  _DBUS_ZERO (addr);
505
  addr.sun_family = AF_UNIX;
506 507 508 509
  
  if (abstract)
    {
#ifdef HAVE_ABSTRACT_SOCKETS
510 511 512
      /* remember that abstract names aren't nul-terminated so we rely
       * on sun_path being filled in with zeroes above.
       */
513 514
      addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
      strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
515
      /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
#else /* HAVE_ABSTRACT_SOCKETS */
      dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
                      "Operating system does not support abstract socket namespace\n");
      close (listen_fd);
      return -1;
#endif /* ! HAVE_ABSTRACT_SOCKETS */
    }
  else
    {
      /* FIXME discussed security implications of this with Nalin,
       * and we couldn't think of where it would kick our ass, but
       * it still seems a bit sucky. It also has non-security suckage;
       * really we'd prefer to exit if the socket is already in use.
       * But there doesn't seem to be a good way to do this.
       *
       * Just to be extra careful, I threw in the stat() - clearly
       * the stat() can't *fix* any security issue, but it at least
       * avoids inadvertent/accidental data loss.
       */
      {
        struct stat sb;

        if (stat (path, &sb) == 0 &&
            S_ISSOCK (sb.st_mode))
          unlink (path);
      }

      strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
    }
545
  
546
  if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
547
    {
548 549 550
      dbus_set_error (error, _dbus_error_from_errno (errno),
                      "Failed to bind socket \"%s\": %s",
                      path, _dbus_strerror (errno));
551 552 553 554 555 556
      close (listen_fd);
      return -1;
    }

  if (listen (listen_fd, 30 /* backlog */) < 0)
    {
557 558 559
      dbus_set_error (error, _dbus_error_from_errno (errno),
                      "Failed to listen on socket \"%s\": %s",
                      path, _dbus_strerror (errno));
560 561 562 563
      close (listen_fd);
      return -1;
    }

564
  if (!_dbus_set_fd_nonblocking (listen_fd, error))
565
    {
566
      _DBUS_ASSERT_ERROR_IS_SET (error);
567 568 569
      close (listen_fd);
      return -1;
    }
570
  
571 572 573
  /* Try opening up the permissions, but if we can't, just go ahead
   * and continue, maybe it will be good enough.
   */
574
  if (!abstract && chmod (path, 0777) < 0)
575 576
    _dbus_warn ("Could not set mode 0777 on socket %s\n",
                path);
577 578 579
  
  return listen_fd;
}
580 581 582 583 584 585 586 587

/**
 * Creates a socket and connects to a socket at the given host 
 * and port. The connection fd is returned, and is set up as
 * nonblocking.
 *
 * @param host the host name to connect to
 * @param port the prot to connect to
588
 * @param error return location for error code
589 590 591 592 593
 * @returns connection file descriptor or -1 on error
 */
int
_dbus_connect_tcp_socket (const char     *host,
                          dbus_uint32_t   port,
594
                          DBusError      *error)
595 596 597 598 599
{
  int fd;
  struct sockaddr_in addr;
  struct hostent *he;
  struct in_addr *haddr;
600 601

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
602 603 604 605 606
  
  fd = socket (AF_INET, SOCK_STREAM, 0);
  
  if (fd < 0)
    {
607 608 609 610
      dbus_set_error (error,
                      _dbus_error_from_errno (errno),
                      "Failed to create socket: %s",
                      _dbus_strerror (errno)); 
611 612 613 614 615 616 617 618 619 620
      
      return -1;
    }

  if (host == NULL)
    host = "localhost";

  he = gethostbyname (host);
  if (he == NULL) 
    {
621 622 623 624
      dbus_set_error (error,
                      _dbus_error_from_errno (errno),
                      "Failed to lookup hostname: %s",
                      host);
625
      close (fd);
626 627 628 629 630 631 632 633 634 635 636 637
      return -1;
    }
  
  haddr = ((struct in_addr *) (he->h_addr_list)[0]);

  _DBUS_ZERO (addr);
  memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
  addr.sin_family = AF_INET;
  addr.sin_port = htons (port);
  
  if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
    {      
638 639 640 641
      dbus_set_error (error,
                       _dbus_error_from_errno (errno),
                      "Failed to connect to socket %s: %s:%d",
                      host, _dbus_strerror (errno), port);
642 643 644 645 646 647 648

      close (fd);
      fd = -1;
      
      return -1;
    }

649
  if (!_dbus_set_fd_nonblocking (fd, error))
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
    {
      close (fd);
      fd = -1;

      return -1;
    }

  return fd;
}

/**
 * Creates a socket and binds it to the given path,
 * then listens on the socket. The socket is
 * set to be nonblocking. 
 *
 * @param host the host name to listen on
 * @param port the prot to listen on
667
 * @param error return location for errors
668 669 670 671 672
 * @returns the listening file descriptor or -1 on error
 */
int
_dbus_listen_tcp_socket (const char     *host,
                         dbus_uint32_t   port,
673
                         DBusError      *error)
674 675 676 677 678
{
  int listen_fd;
  struct sockaddr_in addr;
  struct hostent *he;
  struct in_addr *haddr;
679 680

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
681 682 683 684 685
  
  listen_fd = socket (AF_INET, SOCK_STREAM, 0);
  
  if (listen_fd < 0)
    {
686 687 688
      dbus_set_error (error, _dbus_error_from_errno (errno),
                      "Failed to create socket \"%s:%d\": %s",
                      host, port, _dbus_strerror (errno));
689 690 691 692 693 694
      return -1;
    }

  he = gethostbyname (host);
  if (he == NULL) 
    {
695 696 697 698
      dbus_set_error (error,
                      _dbus_error_from_errno (errno),
                      "Failed to lookup hostname: %s",
                      host);
699
      close (listen_fd);
700 701 702 703 704 705 706 707 708 709 710 711
      return -1;
    }
  
  haddr = ((struct in_addr *) (he->h_addr_list)[0]);

  _DBUS_ZERO (addr);
  memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
  addr.sin_family = AF_INET;
  addr.sin_port = htons (port);

  if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
    {
712 713 714
      dbus_set_error (error, _dbus_error_from_errno (errno),
                      "Failed to bind socket \"%s:%d\": %s",
                      host, port, _dbus_strerror (errno));
715 716 717 718 719 720
      close (listen_fd);
      return -1;
    }

  if (listen (listen_fd, 30 /* backlog */) < 0)
    {
721 722 723
      dbus_set_error (error, _dbus_error_from_errno (errno),  
                      "Failed to listen on socket \"%s:%d\": %s",
                      host, port, _dbus_strerror (errno));
724 725 726 727
      close (listen_fd);
      return -1;
    }

728
  if (!_dbus_set_fd_nonblocking (listen_fd, error))
729 730 731 732 733 734 735
    {
      close (listen_fd);
      return -1;
    }
  
  return listen_fd;
}
736

737 738
static dbus_bool_t
write_credentials_byte (int             server_fd,
739
                        DBusError      *error)
740 741 742
{
  int bytes_written;
  char buf[1] = { '\0' };
743 744

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
745 746 747 748 749 750 751 752 753 754
  
 again:

  bytes_written = write (server_fd, buf, 1);

  if (bytes_written < 0 && errno == EINTR)
    goto again;

  if (bytes_written < 0)
    {
755 756
      dbus_set_error (error, _dbus_error_from_errno (errno),
                      "Failed to write credentials byte: %s",
757 758 759 760 761
                     _dbus_strerror (errno));
      return FALSE;
    }
  else if (bytes_written == 0)
    {
762 763
      dbus_set_error (error, DBUS_ERROR_IO_ERROR,
                      "wrote zero bytes writing credentials byte");
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
      return FALSE;
    }
  else
    {
      _dbus_assert (bytes_written == 1);
      _dbus_verbose ("wrote credentials byte\n");
      return TRUE;
    }
}

/**
 * Reads a single byte which must be nul (an error occurs otherwise),
 * and reads unix credentials if available. Fills in pid/uid/gid with
 * -1 if no credentials are available. Return value indicates whether
 * a byte was read, not whether we got valid credentials. On some
 * systems, such as Linux, reading/writing the byte isn't actually
 * required, but we do it anyway just to avoid multiple codepaths.
 * 
 * Fails if no byte is available, so you must select() first.
 *
 * The point of the byte is that on some systems we have to
 * use sendmsg()/recvmsg() to transmit credentials.
 *
 * @param client_fd the client file descriptor
 * @param credentials struct to fill with credentials of client
789
 * @param error location to store error code
790 791 792 793 794
 * @returns #TRUE on success
 */
dbus_bool_t
_dbus_read_credentials_unix_socket  (int              client_fd,
                                     DBusCredentials *credentials,
795
                                     DBusError       *error)
796
{
797 798 799 800 801 802 803 804 805
  struct msghdr msg;
  struct iovec iov;
  char buf;

#ifdef HAVE_CMSGCRED 
  char cmsgmem[CMSG_SPACE (sizeof (struct cmsgcred))];
  struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
#endif

806 807
  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
  
808 809 810 811 812 813 814
  /* The POSIX spec certainly doesn't promise this, but
   * we need these assertions to fail as soon as we're wrong about
   * it so we can do the porting fixups
   */
  _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
  _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
  _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
815 816

  _dbus_credentials_clear (credentials);
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848

#if defined(LOCAL_CREDS) && defined(HAVE_CMSGCRED)
  /* Set the socket to receive credentials on the next message */
  {
    int on = 1;
    if (setsockopt (client_fd, 0, LOCAL_CREDS, &on, sizeof (on)) < 0)
      {
	_dbus_verbose ("Unable to set LOCAL_CREDS socket option\n");
	return FALSE;
      }
  }
#endif

  iov.iov_base = &buf;
  iov.iov_len = 1;

  memset (&msg, 0, sizeof (msg));
  msg.msg_iov = &iov;
  msg.msg_iovlen = 1;

#ifdef HAVE_CMSGCRED
  memset (cmsgmem, 0, sizeof (cmsgmem));
  msg.msg_control = cmsgmem;
  msg.msg_controllen = sizeof (cmsgmem);
#endif

 again:
  if (recvmsg (client_fd, &msg, 0) < 0)
    {
      if (errno == EINTR)
	goto again;

849 850 851
      dbus_set_error (error, _dbus_error_from_errno (errno),
                      "Failed to read credentials byte: %s",
                      _dbus_strerror (errno));
852 853 854 855 856
      return FALSE;
    }

  if (buf != '\0')
    {
857 858
      dbus_set_error (error, DBUS_ERROR_FAILED,
                      "Credentials byte was not nul");
859 860 861 862 863
      return FALSE;
    }

#ifdef HAVE_CMSGCRED
  if (cmsg->cmsg_len < sizeof (cmsgmem) || cmsg->cmsg_type != SCM_CREDS)
864
    {
865
      dbus_set_error (error, DBUS_ERROR_FAILED);
866 867 868 869 870 871 872 873
      _dbus_verbose ("Message from recvmsg() was not SCM_CREDS\n");
      return FALSE;
    }
#endif

  _dbus_verbose ("read credentials byte\n");

  {
874
#ifdef SO_PEERCRED
875 876
    struct ucred cr;   
    int cr_len = sizeof (cr);
877
   
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
    if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
	cr_len == sizeof (cr))
      {
	credentials->pid = cr.pid;
	credentials->uid = cr.uid;
	credentials->gid = cr.gid;
      }
    else
      {
	_dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
		       cr_len, (int) sizeof (cr), _dbus_strerror (errno));
      }
#elif defined(HAVE_CMSGCRED)
    struct cmsgcred *cred;

    cred = (struct cmsgcred *) CMSG_DATA (cmsg);

    credentials->pid = cred->cmcred_pid;
    credentials->uid = cred->cmcred_euid;
    credentials->gid = cred->cmcred_groups[0];
#else /* !SO_PEERCRED && !HAVE_CMSGCRED */
    _dbus_verbose ("Socket credentials not supported on this OS\n");
900
#endif
901
  }
902

903 904 905 906
  _dbus_verbose ("Credentials:"
                 "  pid "DBUS_PID_FORMAT
                 "  uid "DBUS_UID_FORMAT
                 "  gid "DBUS_GID_FORMAT"\n",
907 908 909 910 911
		 credentials->pid,
		 credentials->uid,
		 credentials->gid);
    
  return TRUE;
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
}

/**
 * Sends a single nul byte with our UNIX credentials as ancillary
 * data.  Returns #TRUE if the data was successfully written.  On
 * systems that don't support sending credentials, just writes a byte,
 * doesn't send any credentials.  On some systems, such as Linux,
 * reading/writing the byte isn't actually required, but we do it
 * anyway just to avoid multiple codepaths.
 *
 * Fails if no byte can be written, so you must select() first.
 *
 * The point of the byte is that on some systems we have to
 * use sendmsg()/recvmsg() to transmit credentials.
 *
 * @param server_fd file descriptor for connection to server
928
 * @param error return location for error code
929 930 931 932
 * @returns #TRUE if the byte was sent
 */
dbus_bool_t
_dbus_send_credentials_unix_socket  (int              server_fd,
933
                                     DBusError       *error)
934
{
935 936 937
  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
  
  if (write_credentials_byte (server_fd, error))
938 939 940 941 942
    return TRUE;
  else
    return FALSE;
}

943
/**
944 945
 * Accepts a connection on a listening socket.
 * Handles EINTR for you.
946 947 948 949 950
 *
 * @param listen_fd the listen file descriptor
 * @returns the connection fd of the client, or -1 on error
 */
int
951
_dbus_accept  (int listen_fd)
952 953
{
  int client_fd;
954 955 956 957
  struct sockaddr addr;
  socklen_t addrlen;

  addrlen = sizeof (addr);
958 959
  
 retry:
960
  client_fd = accept (listen_fd, &addr, &addrlen);
961 962 963 964 965 966
  
  if (client_fd < 0)
    {
      if (errno == EINTR)
        goto retry;
    }
967
  
968 969 970
  return client_fd;
}

971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
/** @} */

/**
 * @addtogroup DBusString
 *
 * @{
 */
/**
 * Appends an integer to a DBusString.
 * 
 * @param str the string
 * @param value the integer value
 * @returns #FALSE if not enough memory or other failure.
 */
dbus_bool_t
_dbus_string_append_int (DBusString *str,
                         long        value)
{
  /* this calculation is from comp.lang.c faq */
#define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1)  /* +1 for '-' */
  int orig_len;
  int i;
  char *buf;
  
  orig_len = _dbus_string_get_length (str);

  if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
    return FALSE;

1000
  buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015

  snprintf (buf, MAX_LONG_LEN, "%ld", value);

  i = 0;
  while (*buf)
    {
      ++buf;
      ++i;
    }
  
  _dbus_string_shorten (str, MAX_LONG_LEN - i);
  
  return TRUE;
}

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
/**
 * Appends an unsigned integer to a DBusString.
 * 
 * @param str the string
 * @param value the integer value
 * @returns #FALSE if not enough memory or other failure.
 */
dbus_bool_t
_dbus_string_append_uint (DBusString    *str,
                          unsigned long  value)
{
  /* this is wrong, but definitely on the high side. */
#define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
  int orig_len;
  int i;
  char *buf;
  
  orig_len = _dbus_string_get_length (str);

  if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
    return FALSE;

1038
  buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053

  snprintf (buf, MAX_ULONG_LEN, "%lu", value);

  i = 0;
  while (*buf)
    {
      ++buf;
      ++i;
    }
  
  _dbus_string_shorten (str, MAX_ULONG_LEN - i);
  
  return TRUE;
}

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
/**
 * Appends a double to a DBusString.
 * 
 * @param str the string
 * @param value the floating point value
 * @returns #FALSE if not enough memory or other failure.
 */
dbus_bool_t
_dbus_string_append_double (DBusString *str,
                            double      value)
{
#define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
  int orig_len;
  char *buf;
  int i;
  
  orig_len = _dbus_string_get_length (str);

  if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
    return FALSE;

1075
  buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112

  snprintf (buf, MAX_LONG_LEN, "%g", value);

  i = 0;
  while (*buf)
    {
      ++buf;
      ++i;
    }
  
  _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
  
  return TRUE;
}

/**
 * Parses an integer contained in a DBusString. Either return parameter
 * may be #NULL if you aren't interested in it. The integer is parsed
 * and stored in value_return. Return parameters are not initialized
 * if the function returns #FALSE.
 *
 * @param str the string
 * @param start the byte index of the start of the integer
 * @param value_return return location of the integer value or #NULL
 * @param end_return return location of the end of the integer, or #NULL
 * @returns #TRUE on success
 */
dbus_bool_t
_dbus_string_parse_int (const DBusString *str,
                        int               start,
                        long             *value_return,
                        int              *end_return)
{
  long v;
  const char *p;
  char *end;

1113 1114
  p = _dbus_string_get_const_data_len (str, start,
                                       _dbus_string_get_length (str) - start);
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124

  end = NULL;
  errno = 0;
  v = strtol (p, &end, 0);
  if (end == NULL || end == p || errno != 0)
    return FALSE;

  if (value_return)
    *value_return = v;
  if (end_return)
1125
    *end_return = start + (end - p);
1126 1127 1128 1129

  return TRUE;
}

1130 1131
#ifdef DBUS_BUILD_TESTS
/* Not currently used, so only built when tests are enabled */
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
/**
 * Parses an unsigned integer contained in a DBusString. Either return
 * parameter may be #NULL if you aren't interested in it. The integer
 * is parsed and stored in value_return. Return parameters are not
 * initialized if the function returns #FALSE.
 *
 * @param str the string
 * @param start the byte index of the start of the integer
 * @param value_return return location of the integer value or #NULL
 * @param end_return return location of the end of the integer, or #NULL
 * @returns #TRUE on success
 */
dbus_bool_t
_dbus_string_parse_uint (const DBusString *str,
                         int               start,
                         unsigned long    *value_return,
                         int              *end_return)
{
  unsigned long v;
  const char *p;
  char *end;

1154 1155
  p = _dbus_string_get_const_data_len (str, start,
                                       _dbus_string_get_length (str) - start);
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169

  end = NULL;
  errno = 0;
  v = strtoul (p, &end, 0);
  if (end == NULL || end == p || errno != 0)
    return FALSE;

  if (value_return)
    *value_return = v;
  if (end_return)
    *end_return = start + (end - p);

  return TRUE;
}
1170
#endif /* DBUS_BUILD_TESTS */
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 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
static dbus_bool_t
ascii_isspace (char c)
{
  return (c == ' ' ||
	  c == '\f' ||
	  c == '\n' ||
	  c == '\r' ||
	  c == '\t' ||
	  c == '\v');
}

static dbus_bool_t
ascii_isdigit (char c)
{
  return c >= '0' && c <= '9';
}

static dbus_bool_t
ascii_isxdigit (char c)
{
  return (ascii_isdigit (c) ||
	  (c >= 'a' && c <= 'f') ||
	  (c >= 'A' && c <= 'F'));
}


/* Calls strtod in a locale-independent fashion, by looking at
 * the locale data and patching the decimal comma to a point.
 *
 * Relicensed from glib.
 */
static double
ascii_strtod (const char *nptr,
	      char      **endptr)
{
  char *fail_pos;
  double val;
  struct lconv *locale_data;
  const char *decimal_point;
  int decimal_point_len;
  const char *p, *decimal_point_pos;
  const char *end = NULL; /* Silence gcc */

  fail_pos = NULL;

  locale_data = localeconv ();
  decimal_point = locale_data->decimal_point;
  decimal_point_len = strlen (decimal_point);

  _dbus_assert (decimal_point_len != 0);
  
  decimal_point_pos = NULL;
  if (decimal_point[0] != '.' ||
      decimal_point[1] != 0)
    {
      p = nptr;
      /* Skip leading space */
      while (ascii_isspace (*p))
	p++;
      
      /* Skip leading optional sign */
      if (*p == '+' || *p == '-')
	p++;
      
      if (p[0] == '0' &&
	  (p[1] == 'x' || p[1] == 'X'))
	{
	  p += 2;
	  /* HEX - find the (optional) decimal point */
	  
	  while (ascii_isxdigit (*p))
	    p++;
	  
	  if (*p == '.')
	    {
	      decimal_point_pos = p++;
	      
	      while (ascii_isxdigit (*p))
		p++;
	      
	      if (*p == 'p' || *p == 'P')
		p++;
	      if (*p == '+' || *p == '-')
		p++;
	      while (ascii_isdigit (*p))
		p++;
	      end = p;
	    }
	}
      else
	{
	  while (ascii_isdigit (*p))
	    p++;
	  
	  if (*p == '.')
	    {
	      decimal_point_pos = p++;
	      
	      while (ascii_isdigit (*p))
		p++;
	      
	      if (*p == 'e' || *p == 'E')
		p++;
	      if (*p == '+' || *p == '-')
		p++;
	      while (ascii_isdigit (*p))
		p++;
	      end = p;
	    }
	}
      /* For the other cases, we need not convert the decimal point */
    }

  /* Set errno to zero, so that we can distinguish zero results
     and underflows */
  errno = 0;
  
  if (decimal_point_pos)
    {
      char *copy, *c;

      /* We need to convert the '.' to the locale specific decimal point */
      copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
      
      c = copy;
      memcpy (c, nptr, decimal_point_pos - nptr);
      c += decimal_point_pos - nptr;
      memcpy (c, decimal_point, decimal_point_len);
      c += decimal_point_len;
      memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
      c += end - (decimal_point_pos + 1);
      *c = 0;

      val = strtod (copy, &fail_pos);

      if (fail_pos)
	{
	  if (fail_pos > decimal_point_pos)
	    fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
	  else
	    fail_pos = (char *)nptr + (fail_pos - copy);
	}
      
      dbus_free (copy);
	  
    }
  else
    val = strtod (nptr, &fail_pos);

  if (endptr)
    *endptr = fail_pos;
  
  return val;
}


1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
/**
 * Parses a floating point number contained in a DBusString. Either
 * return parameter may be #NULL if you aren't interested in it. The
 * integer is parsed and stored in value_return. Return parameters are
 * not initialized if the function returns #FALSE.
 *
 * @param str the string
 * @param start the byte index of the start of the float
 * @param value_return return location of the float value or #NULL
 * @param end_return return location of the end of the float, or #NULL
 * @returns #TRUE on success
 */
dbus_bool_t
_dbus_string_parse_double (const DBusString *str,
                           int               start,
                           double           *value_return,
                           int              *end_return)
{
  double v;
  const char *p;
  char *end;

1350 1351
  p = _dbus_string_get_const_data_len (str, start,
                                       _dbus_string_get_length (str) - start);
1352 1353 1354

  end = NULL;
  errno = 0;
1355
  v = ascii_strtod (p, &end);
1356 1357 1358 1359 1360 1361
  if (end == NULL || end == p || errno != 0)
    return FALSE;

  if (value_return)
    *value_return = v;
  if (end_return)
1362
    *end_return = start + (end - p);
1363 1364 1365 1366

  return TRUE;
}

1367 1368 1369 1370 1371 1372
/** @} */ /* DBusString group */

/**
 * @addtogroup DBusInternalsUtils
 * @{
 */
1373
static dbus_bool_t
1374 1375 1376
fill_user_info_from_passwd (struct passwd *p,
                            DBusUserInfo  *info,
                            DBusError     *error)
1377
{
1378 1379
  _dbus_assert (p->pw_name != NULL);
  _dbus_assert (p->pw_dir != NULL);
1380
  
1381 1382 1383 1384
  info->uid = p->pw_uid;
  info->primary_gid = p->pw_gid;
  info->username = _dbus_strdup (p->pw_name);
  info->homedir = _dbus_strdup (p->pw_dir);
1385
  
1386 1387
  if (info->username == NULL ||
      info->homedir == NULL)
1388
    {
1389
      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1390 1391 1392 1393 1394
      return FALSE;
    }

  return TRUE;
}
1395

1396
static dbus_bool_t
1397 1398 1399 1400
fill_user_info (DBusUserInfo       *info,
                dbus_uid_t          uid,
                const DBusString   *username,
                DBusError          *error)
1401
{
1402 1403
  const char *username_c;
  
1404
  /* exactly one of username/uid provided */
1405
  _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1406
  _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1407

1408 1409 1410 1411 1412 1413
  info->uid = DBUS_UID_UNSET;
  info->primary_gid = DBUS_GID_UNSET;
  info->group_ids = NULL;
  info->n_group_ids = 0;
  info->username = NULL;
  info->homedir = NULL;
1414 1415
  
  if (username != NULL)
1416
    username_c = _dbus_string_get_const_data (username);
1417
  else
1418
    username_c = NULL;
1419 1420 1421 1422 1423

  /* For now assuming that the getpwnam() and getpwuid() flavors
   * are always symmetrical, if not we have to add more configure
   * checks
   */
1424
  
1425
#if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1426 1427 1428 1429 1430 1431 1432
  {
    struct passwd *p;
    int result;
    char buf[1024];
    struct passwd p_str;

    p = NULL;
1433
#ifdef HAVE_POSIX_GETPWNAME_R
1434 1435 1436 1437
    if (uid >= 0)
      result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
                           &p);
    else
1438
      result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
1439
                           &p);
1440
#else
1441
    if (uid != DBUS_UID_UNSET)
1442 1443
      p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
    else
1444
      p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
1445
    result = 0;
1446
#endif /* !HAVE_POSIX_GETPWNAME_R */
1447 1448
    if (result == 0 && p == &p_str)
      {
1449 1450
        if (!fill_user_info_from_passwd (p, info, error))
          return FALSE;
1451 1452 1453
      }
    else
      {