2007-07-12 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / dbus / dbus-sysdeps.c
index f551c4b..cd3e20e 100644 (file)
@@ -1,9 +1,10 @@
 /* -*- mode: C; c-file-style: "gnu" -*- */
-/* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
+/* dbus-sysdeps.c Wrappers around system/libc features shared between UNIX and Windows (internal to D-Bus implementation)
  * 
- * Copyright (C) 2002, 2003  Red Hat, Inc.
+ * Copyright (C) 2002, 2003, 2006  Red Hat, Inc.
+ * Copyright (C) 2003 CodeFactory AB
  *
- * Licensed under the Academic Free License version 1.2
+ * Licensed under the Academic Free License version 2.1
  * 
  * 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
 #include "dbus-internals.h"
 #include "dbus-sysdeps.h"
 #include "dbus-threads.h"
-#include <sys/types.h>
+#include "dbus-protocol.h"
+#include "dbus-string.h"
+#include "dbus-list.h"
+
+/* NOTE: If you include any unix/windows-specific headers here, you are probably doing something
+ * wrong and should be putting some code in dbus-sysdeps-unix.c or dbus-sysdeps-win.c.
+ *
+ * These are the standard ANSI C headers...
+ */
+#include <locale.h>
 #include <stdlib.h>
 #include <string.h>
-#include <signal.h>
-#include <unistd.h>
 #include <stdio.h>
-#include <errno.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <sys/socket.h>
-#include <dirent.h>
-#include <sys/un.h>
-#include <pwd.h>
-#include <time.h>
-#include <sys/time.h>
-#include <sys/stat.h>
-#include <sys/wait.h>
-#include <netinet/in.h>
-#include <netdb.h>
-#include <grp.h>
-
-#ifdef HAVE_WRITEV
-#include <sys/uio.h>
-#endif
-#ifdef HAVE_POLL
-#include <sys/poll.h>
-#endif
-#ifdef HAVE_BACKTRACE
-#include <execinfo.h>
-#endif
-
 
-#ifndef O_BINARY
-#define O_BINARY 0
+/* This is UNIX-specific (on windows it's just in stdlib.h I believe)
+ * but OK since the same stuff does exist on Windows in stdlib.h
+ * and covered by a configure check.
+ */
+#ifdef HAVE_ERRNO_H
+#include <errno.h>
 #endif
 
-#ifndef SUN_LEN
-/* This system is not POSIX.1g.         */
-#define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path)  \
-       + strlen ((ptr)->sun_path))
-#endif
+_DBUS_DEFINE_GLOBAL_LOCK (win_fds);
+_DBUS_DEFINE_GLOBAL_LOCK (sid_atom_cache);
+_DBUS_DEFINE_GLOBAL_LOCK (system_users);
 
 /**
- * @addtogroup DBusInternalsUtils
+ * @defgroup DBusSysdeps Internal system-dependent API
+ * @ingroup DBusInternals
+ * @brief Internal system-dependent API available on UNIX and Windows
+ *
+ * The system-dependent API has a dual purpose. First, it encapsulates
+ * all usage of operating system APIs for ease of auditing and to
+ * avoid cluttering the rest of the code with bizarre OS quirks and
+ * headers. Second, it abstracts different operating system APIs for
+ * portability.
+ * 
  * @{
  */
+
 /**
  * Aborts the program with SIGABRT (dumping core).
  */
 void
 _dbus_abort (void)
 {
+  const char *s;
+  
+  _dbus_print_backtrace ();
+  
+  s = _dbus_getenv ("DBUS_BLOCK_ON_ABORT");
+  if (s && *s)
+    {
+      /* don't use _dbus_warn here since it can _dbus_abort() */
+      fprintf (stderr, "  Process %lu sleeping for gdb attach\n", _dbus_pid_for_log ());
+      _dbus_sleep_milliseconds (1000 * 180);
+    }
+  
   abort ();
-  _exit (1); /* in case someone manages to ignore SIGABRT */
+  _dbus_exit (1); /* in case someone manages to ignore SIGABRT ? */
 }
 
 /**
- * Wrapper for setenv().
+ * Wrapper for setenv(). If the value is #NULL, unsets
+ * the environment variable.
+ *
+ * There is an unfixable memleak in that it is unsafe to
+ * free memory malloced for use with setenv. This is because
+ * we can not rely on internal implementation details of
+ * the underlying libc library.
  *
  * @param varname name of environment variable
  * @param value value of environment variable
  * @returns #TRUE on success.
  */
 dbus_bool_t
-_dbus_setenv (const char *varname, const char *value)
+_dbus_setenv (const char *varname,
+              const char *value)
 {
-#ifdef HAVE_SETENV
-  return (setenv (varname, value, TRUE) == 0);
+  _dbus_assert (varname != NULL);
+  
+  if (value == NULL)
+    {
+#ifdef HAVE_UNSETENV
+      unsetenv (varname);
+      return TRUE;
 #else
-  DBusString str;
-  char *putenv_value;
+      char *putenv_value;
+      size_t len;
 
-  if (!_dbus_string_init (&str))
-    return FALSE;
+      len = strlen (varname);
 
-  if (!_dbus_string_append (&str, varname) ||
-      !_dbus_string_append (&str, "=") ||
-      !_dbus_string_append (&str, value) ||
-      !_dbus_string_steal_data (&str, &putenv_value))
-    {
-      _dbus_string_free (&str);
-      return FALSE;
+      /* Use system malloc to avoid memleaks that dbus_malloc
+       * will get upset about.
+       */
+      
+      putenv_value = malloc (len + 2);
+      if (putenv_value == NULL)
+        return FALSE;
+
+      strcpy (putenv_value, varname);
+#if defined(DBUS_WIN)
+      strcat (putenv_value, "=");
+#endif
+      
+      return (putenv (putenv_value) == 0);
+#endif
     }
+  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;
 
-  _dbus_string_free (&str);
+      varname_len = strlen (varname);
+      value_len = strlen (value);
+      
+      len = varname_len + value_len + 1 /* '=' */ ;
+
+      /* Use system malloc to avoid memleaks that dbus_malloc
+       * will get upset about.
+       */
+      
+      putenv_value = malloc (len + 1);
+      if (putenv_value == NULL)
+        return FALSE;
 
-  return (putenv (putenv_value) == 0);
+      strcpy (putenv_value, varname);
+      strcpy (putenv_value + varname_len, "=");
+      strcpy (putenv_value + varname_len + 1, value);
+      
+      return (putenv (putenv_value) == 0);
 #endif
+    }
 }
 
 /**
@@ -126,703 +177,185 @@ _dbus_getenv (const char *varname)
   return getenv (varname);
 }
 
-/**
- * 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
- * _dbus_read() handles EINTR for you. _dbus_read() can
- * return ENOMEM, even though regular UNIX read doesn't.
+/*
+ * init a pipe instance.
  *
- * @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;
-    }
-
-  data = _dbus_string_get_data_len (buffer, start, count);
-
- 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);
-
-#if 0
-      if (bytes_read > 0)
-        _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
-#endif
-      
-      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
+ * @param pipe the pipe
+ * @param fd the file descriptor to init from 
  */
-int
-_dbus_write (int               fd,
-             const DBusString *buffer,
-             int               start,
-             int               len)
+void
+_dbus_pipe_init (DBusPipe *pipe,
+                 int       fd)
 {
-  const char *data;
-  int bytes_written;
-  
-  data = _dbus_string_get_const_data_len (buffer, start, len);
-  
- again:
-
-  bytes_written = write (fd, data, len);
-
-  if (bytes_written < 0 && errno == EINTR)
-    goto again;
-
-#if 0
-  if (bytes_written > 0)
-    _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
-#endif
-  
-  return bytes_written;
+  pipe->fd_or_handle = fd;
 }
 
 /**
- * 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.
+ * init a pipe with stdout
  *
- * @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
+ * @param pipe the pipe
  */
-int
-_dbus_write_two (int               fd,
-                 const DBusString *buffer1,
-                 int               start1,
-                 int               len1,
-                 const DBusString *buffer2,
-                 int               start2,
-                 int               len2)
+void
+_dbus_pipe_init_stdout (DBusPipe *pipe)
 {
-  _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;
-
-    data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
-
-    if (buffer2 != NULL)
-      data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
-    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);
-
-    if (bytes_written < 0 && errno == EINTR)
-      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 */   
+  _dbus_pipe_init (pipe, 1);
 }
 
 /**
- * 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.
+ * check if a pipe is valid; pipes can be set invalid, similar to
+ * a -1 file descriptor.
  *
- * @param path the path to UNIX domain socket
- * @param error return location for error code
- * @returns connection file descriptor or -1 on error
+ * @param pipe the pipe instance
+ * @returns #FALSE if pipe is not valid
  */
-int
-_dbus_connect_unix_socket (const char     *path,
-                           DBusError      *error)
+dbus_bool_t
+_dbus_pipe_is_valid(DBusPipe *pipe)
 {
-  int fd;
-  struct sockaddr_un addr;  
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  fd = socket (PF_UNIX, SOCK_STREAM, 0);
-  
-  if (fd < 0)
-    {
-      dbus_set_error (error,
-                      _dbus_error_from_errno (errno),
-                      "Failed to create socket: %s",
-                      _dbus_strerror (errno)); 
-      
-      return -1;
-    }
-
-  _DBUS_ZERO (addr);
-  addr.sun_family = AF_UNIX;
-  strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
-  addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
-  
-  if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
-    {      
-      dbus_set_error (error,
-                      _dbus_error_from_errno (errno),
-                      "Failed to connect to socket %s: %s",
-                      path, _dbus_strerror (errno));
-
-      close (fd);
-      fd = -1;
-      
-      return -1;
-    }
-
-  if (!_dbus_set_fd_nonblocking (fd, error))
-    {
-      _DBUS_ASSERT_ERROR_IS_SET (error);
-      
-      close (fd);
-      fd = -1;
-
-      return -1;
-    }
-
-  return fd;
+  return pipe->fd_or_handle >= 0;
 }
 
 /**
- * Creates a socket and binds it to the given path,
- * then listens on the socket. The socket is
- * set to be nonblocking. 
+ * Check if a pipe is stdout or stderr.
  *
- * @param path the socket name
- * @param error return location for errors
- * @returns the listening file descriptor or -1 on error
+ * @param pipe the pipe instance
+ * @returns #TRUE if pipe is one of the standard out/err channels
  */
-int
-_dbus_listen_unix_socket (const char     *path,
-                          DBusError      *error)
+dbus_bool_t
+_dbus_pipe_is_stdout_or_stderr (DBusPipe *pipe)
 {
-  int listen_fd;
-  struct sockaddr_un addr;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
-  
-  if (listen_fd < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to create socket \"%s\": %s",
-                      path, _dbus_strerror (errno));
-      return -1;
-    }
-
-  _DBUS_ZERO (addr);
-  addr.sun_family = AF_UNIX;
-  strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
-  addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
-  
-  if (bind (listen_fd, (struct sockaddr*) &addr, SUN_LEN (&addr)) < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to bind socket \"%s\": %s",
-                      path, _dbus_strerror (errno));
-      close (listen_fd);
-      return -1;
-    }
-
-  if (listen (listen_fd, 30 /* backlog */) < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to listen on socket \"%s\": %s",
-                      path, _dbus_strerror (errno));
-      close (listen_fd);
-      return -1;
-    }
-
-  if (!_dbus_set_fd_nonblocking (listen_fd, error))
-    {
-      _DBUS_ASSERT_ERROR_IS_SET (error);
-      close (listen_fd);
-      return -1;
-    }
-  
-  return listen_fd;
+  return pipe->fd_or_handle == 1 || pipe->fd_or_handle == 2;
 }
 
 /**
- * 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
- * @param error return location for error code
- * @returns connection file descriptor or -1 on error
+ * Initializes a pipe to an invalid value.
+ * @param pipe the pipe
  */
-int
-_dbus_connect_tcp_socket (const char     *host,
-                          dbus_uint32_t   port,
-                          DBusError      *error)
+void
+_dbus_pipe_invalidate (DBusPipe *pipe)
 {
-  int fd;
-  struct sockaddr_in addr;
-  struct hostent *he;
-  struct in_addr *haddr;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  fd = socket (AF_INET, SOCK_STREAM, 0);
-  
-  if (fd < 0)
-    {
-      dbus_set_error (error,
-                      _dbus_error_from_errno (errno),
-                      "Failed to create socket: %s",
-                      _dbus_strerror (errno)); 
-      
-      return -1;
-    }
-
-  if (host == NULL)
-    host = "localhost";
-
-  he = gethostbyname (host);
-  if (he == NULL) 
-    {
-      dbus_set_error (error,
-                      _dbus_error_from_errno (errno),
-                      "Failed to lookup hostname: %s",
-                      host);
-      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)
-    {      
-      dbus_set_error (error,
-                       _dbus_error_from_errno (errno),
-                      "Failed to connect to socket %s: %s:%d",
-                      host, _dbus_strerror (errno), port);
-
-      close (fd);
-      fd = -1;
-      
-      return -1;
-    }
-
-  if (!_dbus_set_fd_nonblocking (fd, error))
-    {
-      close (fd);
-      fd = -1;
-
-      return -1;
-    }
-
-  return fd;
+  pipe->fd_or_handle = -1;
 }
 
 /**
- * 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
- * @param error return location for errors
- * @returns the listening file descriptor or -1 on error
+ * Split paths into a list of char strings
+ * 
+ * @param dirs string with pathes 
+ * @param suffix string concated to each path in dirs
+ * @param dir_list contains a list of splitted pathes
+ * return #TRUE is pathes could be splittes,#FALSE in oom case 
  */
-int
-_dbus_listen_tcp_socket (const char     *host,
-                         dbus_uint32_t   port,
-                         DBusError      *error)
+dbus_bool_t
+_dbus_split_paths_and_append (DBusString *dirs, 
+                              const char *suffix, 
+                              DBusList  **dir_list)
 {
-  int listen_fd;
-  struct sockaddr_in addr;
-  struct hostent *he;
-  struct in_addr *haddr;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  listen_fd = socket (AF_INET, SOCK_STREAM, 0);
-  
-  if (listen_fd < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to create socket \"%s:%d\": %s",
-                      host, port, _dbus_strerror (errno));
-      return -1;
-    }
-
-  if (host == NULL)
-    host = "localhost";
-  
-  he = gethostbyname (host);
-  if (he == NULL) 
-    {
-      dbus_set_error (error,
-                      _dbus_error_from_errno (errno),
-                      "Failed to lookup hostname: %s",
-                      host);
-      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)))
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to bind socket \"%s:%d\": %s",
-                      host, port, _dbus_strerror (errno));
-      close (listen_fd);
-      return -1;
-    }
-
-  if (listen (listen_fd, 30 /* backlog */) < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),  
-                      "Failed to listen on socket \"%s:%d\": %s",
-                      host, port, _dbus_strerror (errno));
-      close (listen_fd);
-      return -1;
-    }
+   int start;
+   int i;
+   int len;
+   char *cpath;
+   DBusString file_suffix;
 
-  if (!_dbus_set_fd_nonblocking (listen_fd, error))
-    {
-      close (listen_fd);
-      return -1;
-    }
-  
-  return listen_fd;
-}
+   start = 0;
+   i = 0;
 
-static dbus_bool_t
-write_credentials_byte (int             server_fd,
-                        DBusError      *error)
-{
-  int bytes_written;
-  char buf[1] = { '\0' };
+   _dbus_string_init_const (&file_suffix, suffix);
 
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
- again:
+   len = _dbus_string_get_length (dirs);
 
-  bytes_written = write (server_fd, buf, 1);
+   while (_dbus_string_find (dirs, start, _DBUS_PATH_SEPARATOR, &i))
+     {
+       DBusString path;
 
-  if (bytes_written < 0 && errno == EINTR)
-    goto again;
+       if (!_dbus_string_init (&path))
+          goto oom;
 
-  if (bytes_written < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to write credentials byte: %s",
-                     _dbus_strerror (errno));
-      return FALSE;
-    }
-  else if (bytes_written == 0)
-    {
-      dbus_set_error (error, DBUS_ERROR_IO_ERROR,
-                      "wrote zero bytes writing credentials byte");
-      return FALSE;
-    }
-  else
-    {
-      _dbus_assert (bytes_written == 1);
-      _dbus_verbose ("wrote credentials byte\n");
-      return TRUE;
-    }
-}
+       if (!_dbus_string_copy_len (dirs,
+                                   start,
+                                   i - start,
+                                   &path,
+                                   0))
+          {
+            _dbus_string_free (&path);
+            goto oom;
+          }
 
-/**
- * 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
- * @param error location to store error code
- * @returns #TRUE on success
- */
-dbus_bool_t
-_dbus_read_credentials_unix_socket  (int              client_fd,
-                                     DBusCredentials *credentials,
-                                     DBusError       *error)
-{
-  struct msghdr msg;
-  struct iovec iov;
-  char buf;
+        _dbus_string_chop_white (&path);
 
-#ifdef HAVE_CMSGCRED 
-  char cmsgmem[CMSG_SPACE (sizeof (struct cmsgcred))];
-  struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
-#endif
+        /* check for an empty path */
+        if (_dbus_string_get_length (&path) == 0)
+          goto next;
 
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  /* 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));
-  
-  credentials->pid = -1;
-  credentials->uid = -1;
-  credentials->gid = -1;
-
-#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
+        if (!_dbus_concat_dir_and_file (&path,
+                                        &file_suffix))
+          {
+            _dbus_string_free (&path);
+            goto oom;
+          }
 
-  iov.iov_base = &buf;
-  iov.iov_len = 1;
+        if (!_dbus_string_copy_data(&path, &cpath))
+          {
+            _dbus_string_free (&path);
+            goto oom;
+          }
 
-  memset (&msg, 0, sizeof (msg));
-  msg.msg_iov = &iov;
-  msg.msg_iovlen = 1;
+        if (!_dbus_list_append (dir_list, cpath))
+          {
+            _dbus_string_free (&path);              
+            dbus_free (cpath);
+            goto oom;
+          }
 
-#ifdef HAVE_CMSGCRED
-  memset (cmsgmem, 0, sizeof (cmsgmem));
-  msg.msg_control = cmsgmem;
-  msg.msg_controllen = sizeof (cmsgmem);
-#endif
+       next:
+        _dbus_string_free (&path);
+        start = i + 1;
+    } 
+      
+  if (start != len)
+    { 
+      DBusString path;
+
+      if (!_dbus_string_init (&path))
+        goto oom;
+
+      if (!_dbus_string_copy_len (dirs,
+                                  start,
+                                  len - start,
+                                  &path,
+                                  0))
+        {
+          _dbus_string_free (&path);
+          goto oom;
+        }
 
- again:
-  if (recvmsg (client_fd, &msg, 0) < 0)
-    {
-      if (errno == EINTR)
-       goto again;
+      if (!_dbus_concat_dir_and_file (&path,
+                                      &file_suffix))
+        {
+          _dbus_string_free (&path);
+          goto oom;
+        }
 
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to read credentials byte: %s",
-                      _dbus_strerror (errno));
-      return FALSE;
-    }
+      if (!_dbus_string_copy_data(&path, &cpath))
+        {
+          _dbus_string_free (&path);
+          goto oom;
+        }
 
-  if (buf != '\0')
-    {
-      dbus_set_error (error, DBUS_ERROR_FAILED,
-                      "Credentials byte was not nul");
-      return FALSE;
-    }
+      if (!_dbus_list_append (dir_list, cpath))
+        {
+          _dbus_string_free (&path);              
+          dbus_free (cpath);
+          goto oom;
+        }
 
-#ifdef HAVE_CMSGCRED
-  if (cmsg->cmsg_len < sizeof (cmsgmem) || cmsg->cmsg_type != SCM_CREDS)
-    {
-      dbus_set_error (error, DBUS_ERROR_FAILED);
-      _dbus_verbose ("Message from recvmsg() was not SCM_CREDS\n");
-      return FALSE;
+      _dbus_string_free (&path); 
     }
-#endif
-
-  _dbus_verbose ("read credentials byte\n");
-
-  {
-#ifdef SO_PEERCRED
-    struct ucred cr;   
-    int cr_len = sizeof (cr);
-   
-    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");
-#endif
-  }
 
-  _dbus_verbose ("Credentials: pid %d  uid %d  gid %d\n",
-                credentials->pid,
-                credentials->uid,
-                credentials->gid);
-    
   return TRUE;
-}
-
-/**
- * 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
- * @param error return location for error code
- * @returns #TRUE if the byte was sent
- */
-dbus_bool_t
-_dbus_send_credentials_unix_socket  (int              server_fd,
-                                     DBusError       *error)
-{
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  if (write_credentials_byte (server_fd, error))
-    return TRUE;
-  else
-    return FALSE;
-}
-
-/**
- * Accepts a connection on a listening socket.
- * Handles EINTR for you.
- *
- * @param listen_fd the listen file descriptor
- * @returns the connection fd of the client, or -1 on error
- */
-int
-_dbus_accept  (int listen_fd)
-{
-  int client_fd;
-  struct sockaddr addr;
-  socklen_t addrlen;
 
-  addrlen = sizeof (addr);
-  
- retry:
-  client_fd = accept (listen_fd, &addr, &addrlen);
-  
-  if (client_fd < 0)
-    {
-      if (errno == EINTR)
-        goto retry;
-    }
-  
-  return client_fd;
+ oom:
+  _dbus_list_foreach (dir_list, (DBusForeachFunction)dbus_free, NULL); 
+  _dbus_list_clear (dir_list);
+  return FALSE;
 }
 
 /** @} */
@@ -908,6 +441,7 @@ _dbus_string_append_uint (DBusString    *str,
   return TRUE;
 }
 
+#ifdef DBUS_BUILD_TESTS
 /**
  * Appends a double to a DBusString.
  * 
@@ -944,6 +478,7 @@ _dbus_string_append_double (DBusString *str,
   
   return TRUE;
 }
+#endif /* DBUS_BUILD_TESTS */
 
 /**
  * Parses an integer contained in a DBusString. Either return parameter
@@ -1023,1752 +558,325 @@ _dbus_string_parse_uint (const DBusString *str,
   return TRUE;
 }
 
-/**
- * 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.
- *
- * @todo this function is currently locale-dependent. Should
- * ask alexl to relicense g_ascii_strtod() code and put that in
- * here instead, so it's locale-independent.
- *
- * @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;
-
-  _dbus_warn ("_dbus_string_parse_double() needs to be made locale-independent\n");
-  
-  p = _dbus_string_get_const_data_len (str, start,
-                                       _dbus_string_get_length (str) - start);
-
-  end = NULL;
-  errno = 0;
-  v = strtod (p, &end);
-  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;
-}
-
-/** @} */ /* DBusString group */
-
-/**
- * @addtogroup DBusInternalsUtils
- * @{
- */
-
-static dbus_bool_t
-store_user_info (struct passwd    *p,
-                 DBusCredentials  *credentials,
-                 DBusString       *homedir,
-                 DBusString       *username_out)
-{
-  int old_homedir_len;
-  
-  if (credentials != NULL)
-    {
-      credentials->uid = p->pw_uid;
-      credentials->gid = p->pw_gid;
-    }
-
-  old_homedir_len = 0;
-  if (homedir != NULL)
-    {
-      old_homedir_len = _dbus_string_get_length (homedir);
-      
-      if (!_dbus_string_append (homedir, p->pw_dir))
-        {
-          _dbus_verbose ("No memory to get homedir\n");
-          return FALSE;
-        }
-    }
-  
-  if (username_out &&
-      !_dbus_string_append (username_out, p->pw_name))
-    {
-      if (homedir)
-        _dbus_string_set_length (homedir, old_homedir_len);
-      _dbus_verbose ("No memory to get username\n");
-      return FALSE;
-    }
-      
-  _dbus_verbose ("Username %s has uid %d gid %d homedir %s\n",
-                 p->pw_name, (int) p->pw_uid, (int) p->pw_gid,
-                 p->pw_dir);
-
-  return TRUE;
-}
-  
-/**
- * Gets user info using either username or uid. Only
- * one of these may be passed in, either username
- * must be #NULL or uid must be < 0.
- *
- * @param username the username
- * @param uid the user ID
- * @param credentials to fill in or #NULL
- * @param homedir string to append homedir to or #NULL
- * @param username_out string to append username to or #NULL
- *
- * @returns #TRUE on success
- */
-static dbus_bool_t
-get_user_info (const DBusString *username,
-               int               uid,
-               DBusCredentials  *credentials,
-               DBusString       *homedir,
-               DBusString       *username_out)
-{
-  const char *username_c_str;
-      
-  /* exactly one of username/uid provided */
-  _dbus_assert (username != NULL || uid >= 0);
-  _dbus_assert (username == NULL || uid < 0);
-
-  if (credentials)
-    {
-      credentials->pid = -1;
-      credentials->uid = -1;
-      credentials->gid = -1;
-    }
-  
-  if (username != NULL)
-    username_c_str = _dbus_string_get_const_data (username);
-  else
-    username_c_str = NULL;
-
-  /* For now assuming that the getpwnam() and getpwuid() flavors
-   * are always symmetrical, if not we have to add more configure
-   * checks
-   */
-  
-#if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
-  {
-    struct passwd *p;
-    int result;
-    char buf[1024];
-    struct passwd p_str;
-
-    p = NULL;
-#ifdef HAVE_POSIX_GETPWNAME_R
-    if (uid >= 0)
-      result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
-                           &p);
-    else
-      result = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf),
-                           &p);
-#else
-    if (uid >= 0)
-      p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
-    else
-      p = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf));
-    result = 0;
-#endif /* !HAVE_POSIX_GETPWNAME_R */
-    if (result == 0 && p == &p_str)
-      {
-        return store_user_info (p, credentials, homedir,
-                                username_out);
-      }
-    else
-      {
-        _dbus_verbose ("User %s unknown\n", username_c_str);
-        return FALSE;
-      }
-  }
-#else /* ! HAVE_GETPWNAM_R */
-  {
-    /* I guess we're screwed on thread safety here */
-    struct passwd *p;
-
-    if (uid >= 0)
-      p = getpwuid (uid);
-    else
-      p = getpwnam (username_c_str);
-
-    if (p != NULL)
-      {
-        return store_user_info (p, credentials, homedir,
-                                username_out);
-      }
-    else
-      {
-        _dbus_verbose ("User %s unknown\n", username_c_str);
-        return FALSE;
-      }
-  }
-#endif  /* ! HAVE_GETPWNAM_R */
-}
-
-/**
- * Gets the credentials corresponding to the given username.
- *
- * @param username the username
- * @param credentials credentials to fill in
- * @returns #TRUE if the username existed and we got some credentials
- */
-dbus_bool_t
-_dbus_credentials_from_username (const DBusString *username,
-                                 DBusCredentials  *credentials)
-{
-  return get_user_info (username, -1, credentials, NULL, NULL);
-}
-
-/**
- * Gets the credentials corresponding to the given user ID.
- *
- * @param user_id the user ID
- * @param credentials credentials to fill in
- * @returns #TRUE if the username existed and we got some credentials
- */
-dbus_bool_t
-_dbus_credentials_from_user_id (unsigned long     user_id,
-                                DBusCredentials  *credentials)
-{
-  return get_user_info (NULL, user_id, credentials, NULL, NULL);
-}
-
-_DBUS_DEFINE_GLOBAL_LOCK (user_info);
-
-typedef struct
-{
-  DBusString name;
-  DBusString dir;
-  DBusCredentials creds;
-} UserInfo;
-
-static void
-shutdown_user_info (void *data)
-{
-  UserInfo *u = data;
-
-  _dbus_string_free (&u->name);
-  _dbus_string_free (&u->dir);
-}
-
-/**
- * Gets information about the user running this process.
- *
- * @param username return location for username or #NULL
- * @param homedir return location for home directory or #NULL
- * @param credentials return location for credentials or #NULL
- * @returns #TRUE on success
- */
-dbus_bool_t
-_dbus_user_info_from_current_process (const DBusString      **username,
-                                      const DBusString      **homedir,
-                                      const DBusCredentials **credentials)
-{
-  static UserInfo u;
-  static int initialized_generation = 0;
-  
-  if (!_DBUS_LOCK (user_info))
-    return FALSE;
-
-  if (initialized_generation != _dbus_current_generation)
-    {
-      if (!_dbus_string_init (&u.name))
-        {
-          _DBUS_UNLOCK (user_info);
-          return FALSE;
-        }
-
-      if (!_dbus_string_init (&u.dir))
-        {
-          _dbus_string_free (&u.name);
-          _DBUS_UNLOCK (user_info);
-          return FALSE;
-        }
-      
-      u.creds.uid = -1;
-      u.creds.gid = -1;
-      u.creds.pid = -1;
-
-      if (!get_user_info (NULL, getuid (),
-                          &u.creds, &u.dir, &u.name))
-        goto fail_init;
-      
-      if (!_dbus_register_shutdown_func (shutdown_user_info,
-                                         &u))
-        goto fail_init;
-      
-      initialized_generation = _dbus_current_generation;
-    fail_init:
-      if (initialized_generation != _dbus_current_generation)
-        {
-          _dbus_string_free (&u.name);
-          _dbus_string_free (&u.dir);
-          _DBUS_UNLOCK (user_info);
-          return FALSE;
-        }
-    }
-
-  if (username)
-    *username = &u.name;
-  if (homedir)
-    *homedir = &u.dir;
-  if (credentials)
-    *credentials = &u.creds;
-  
-  _DBUS_UNLOCK (user_info);
-
-  return TRUE;
-}
-
-/**
- * Gets the home directory for the given user.
- *
- * @param username the username
- * @param homedir string to append home directory to
- * @returns #TRUE if user existed and we appended their homedir
- */
-dbus_bool_t
-_dbus_homedir_from_username (const DBusString *username,
-                             DBusString       *homedir)
-{
-  return get_user_info (username, -1, NULL, homedir, NULL);
-}
-
-/**
- * Gets credentials from a UID string. (Parses a string to a UID
- * and converts to a DBusCredentials.)
- *
- * @param uid_str the UID in string form
- * @param credentials credentials to fill in
- * @returns #TRUE if successfully filled in some credentials
- */
-dbus_bool_t
-_dbus_credentials_from_uid_string (const DBusString      *uid_str,
-                                   DBusCredentials       *credentials)
-{
-  int end;
-  long uid;
-
-  credentials->pid = -1;
-  credentials->uid = -1;
-  credentials->gid = -1;
-  
-  if (_dbus_string_get_length (uid_str) == 0)
-    {
-      _dbus_verbose ("UID string was zero length\n");
-      return FALSE;
-    }
-
-  uid = -1;
-  end = 0;
-  if (!_dbus_string_parse_int (uid_str, 0, &uid,
-                               &end))
-    {
-      _dbus_verbose ("could not parse string as a UID\n");
-      return FALSE;
-    }
-  
-  if (end != _dbus_string_get_length (uid_str))
-    {
-      _dbus_verbose ("string contained trailing stuff after UID\n");
-      return FALSE;
-    }
-
-  credentials->uid = uid;
-
-  return TRUE;
-}
-
-/**
- * Gets the credentials of the current process.
- *
- * @param credentials credentials to fill in.
- */
-void
-_dbus_credentials_from_current_process (DBusCredentials *credentials)
-{
-  /* 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));
-  
-  credentials->pid = getpid ();
-  credentials->uid = getuid ();
-  credentials->gid = getgid ();
-}
-
-/**
- * Checks whether the provided_credentials are allowed to log in
- * as the expected_credentials.
- *
- * @param expected_credentials credentials we're trying to log in as
- * @param provided_credentials credentials we have
- * @returns #TRUE if we can log in
- */
-dbus_bool_t
-_dbus_credentials_match (const DBusCredentials *expected_credentials,
-                         const DBusCredentials *provided_credentials)
-{
-  if (provided_credentials->uid < 0)
-    return FALSE;
-  else if (expected_credentials->uid < 0)
-    return FALSE;
-  else if (provided_credentials->uid == 0)
-    return TRUE;
-  else if (provided_credentials->uid == expected_credentials->uid)
-    return TRUE;
-  else
-    return FALSE;
-}
-
-/**
- * Gets group ID from group name.
- *
- * @param group_name name of the group
- * @param gid location to store group ID
- * @returns #TRUE if group was known
- */
-dbus_bool_t
-_dbus_get_group_id (const DBusString *group_name,
-                    unsigned long    *gid)
-{
-  const char *group_c_str;
-  
-  group_c_str = _dbus_string_get_const_data (group_name);
-  
-  /* For now assuming that the getgrnam() and getgrgid() flavors
-   * always correspond to the pwnam flavors, if not we have
-   * to add more configure checks.
-   */
-  
-#if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
-  {
-    struct group *g;
-    int result;
-    char buf[1024];
-    struct group g_str;
-
-    g = NULL;
-#ifdef HAVE_POSIX_GETPWNAME_R
-
-    result = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf),
-                         &g);
-#else
-    p = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf));
-    result = 0;
-#endif /* !HAVE_POSIX_GETPWNAME_R */
-    if (result == 0 && g == &g_str)
-      {
-        *gid = g->gr_gid;
-        return TRUE;
-      }
-    else
-      {
-        _dbus_verbose ("Group %s unknown\n", group_c_str);
-        return FALSE;
-      }
-  }
-#else /* ! HAVE_GETPWNAM_R */
-  {
-    /* I guess we're screwed on thread safety here */
-    struct group *g;
-
-    g = getgrnam (group_c_str);
-
-    if (g != NULL)
-      {
-        *gid = g->gr_gid;
-        return TRUE;
-      }
-    else
-      {
-        _dbus_verbose ("Group %s unknown\n", group_c_str);
-        return FALSE;
-      }
-  }
-#endif  /* ! HAVE_GETPWNAM_R */
-}
-
-/**
- * Gets all groups for a particular user. Returns #FALSE
- * if no memory, or user isn't known, but always initializes
- * group_ids to a NULL array.
- *
- * @todo failing to distinguish "out of memory" from
- * "unknown user" is kind of bogus and would probably
- * result in a failure in a comprehensive test suite.
- *
- * @param uid the user ID
- * @param group_ids return location for array of group IDs
- * @param n_group_ids return location for length of returned array
- * @returns #TRUE on success
- */
-dbus_bool_t
-_dbus_get_groups (unsigned long   uid,
-                  unsigned long **group_ids,
-                  int            *n_group_ids)
-{
-  DBusCredentials creds;
-  DBusString username;
-  const char *username_c;
-  dbus_bool_t retval;
-  
-  *group_ids = NULL;
-  *n_group_ids = 0;
-
-  retval = FALSE;
-
-  if (!_dbus_string_init (&username))
-    return FALSE;
-
-  if (!get_user_info (NULL, uid, &creds,
-                      NULL, &username) ||
-      creds.gid < 0)
-    goto out;
-
-  username_c = _dbus_string_get_const_data (&username);
-  
-#ifdef HAVE_GETGROUPLIST
-  {
-    gid_t *buf;
-    int buf_count;
-    int i;
-    
-    buf_count = 17;
-    buf = dbus_new (gid_t, buf_count);
-    if (buf == NULL)
-      goto out;
-    
-    if (getgrouplist (username_c,
-                      creds.gid,
-                      buf, &buf_count) < 0)
-      {
-        gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
-        if (new == NULL)
-          {
-            dbus_free (buf);
-            goto out;
-          }
-        
-        buf = new;
-
-        getgrouplist (username_c, creds.gid, buf, &buf_count);
-      }
-
-    *group_ids = dbus_new (unsigned long, buf_count);
-    if (*group_ids == NULL)
-      {
-        dbus_free (buf);
-        goto out;
-      }
-    
-    for (i = 0; i < buf_count; ++i)
-      (*group_ids)[i] = buf[i];
-
-    *n_group_ids = buf_count;
-    
-    dbus_free (buf);
-  }
-#else  /* HAVE_GETGROUPLIST */
-  {
-    /* We just get the one group ID */
-    *group_ids = dbus_new (unsigned long, 1);
-    if (*group_ids == NULL)
-      goto out;
-
-    *n_group_ids = 1;
-
-    (*group_ids)[0] = creds.gid;
-  }
-#endif /* HAVE_GETGROUPLIST */
-
-    retval = TRUE;
-    
-  out:
-    _dbus_string_free (&username);
-    return retval;
-}
-
-/**
- * Appends the uid of the current process to the given string.
- *
- * @param str the string to append to
- * @returns #TRUE on success
- */
-dbus_bool_t
-_dbus_string_append_our_uid (DBusString *str)
-{
-  return _dbus_string_append_int (str, getuid ());
-}
-
-
-_DBUS_DEFINE_GLOBAL_LOCK (atomic);
-
-/**
- * Atomically increments an integer
- *
- * @param atomic pointer to the integer to increment
- * @returns the value after incrementing
- *
- * @todo implement arch-specific faster atomic ops
- */
-dbus_atomic_t
-_dbus_atomic_inc (dbus_atomic_t *atomic)
-{
-  dbus_atomic_t res;
-  
-  _DBUS_LOCK (atomic);
-  *atomic += 1;
-  res = *atomic;
-  _DBUS_UNLOCK (atomic);
-  return res;
-}
-
-/**
- * Atomically decrement an integer
- *
- * @param atomic pointer to the integer to decrement
- * @returns the value after decrementing
- *
- * @todo implement arch-specific faster atomic ops
- */
-dbus_atomic_t
-_dbus_atomic_dec (dbus_atomic_t *atomic)
-{
-  dbus_atomic_t res;
-  
-  _DBUS_LOCK (atomic);
-  *atomic -= 1;
-  res = *atomic;
-  _DBUS_UNLOCK (atomic);
-  return res;
-}
-
-/**
- * Wrapper for poll().
- *
- * @todo need a fallback implementation using select()
- *
- * @param fds the file descriptors to poll
- * @param n_fds number of descriptors in the array
- * @param timeout_milliseconds timeout or -1 for infinite
- * @returns numbers of fds with revents, or <0 on error
- */
-int
-_dbus_poll (DBusPollFD *fds,
-            int         n_fds,
-            int         timeout_milliseconds)
-{
-#ifdef HAVE_POLL
-  /* This big thing is a constant expression and should get optimized
-   * out of existence. So it's more robust than a configure check at
-   * no cost.
-   */
-  if (_DBUS_POLLIN == POLLIN &&
-      _DBUS_POLLPRI == POLLPRI &&
-      _DBUS_POLLOUT == POLLOUT &&
-      _DBUS_POLLERR == POLLERR &&
-      _DBUS_POLLHUP == POLLHUP &&
-      _DBUS_POLLNVAL == POLLNVAL &&
-      sizeof (DBusPollFD) == sizeof (struct pollfd) &&
-      _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
-      _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
-      _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
-      _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
-      _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
-      _DBUS_STRUCT_OFFSET (struct pollfd, revents))
-    {
-      return poll ((struct pollfd*) fds,
-                   n_fds, 
-                   timeout_milliseconds);
-    }
-  else
-    {
-      /* We have to convert the DBusPollFD to an array of
-       * struct pollfd, poll, and convert back.
-       */
-      _dbus_warn ("didn't implement poll() properly for this system yet\n");
-      return -1;
-    }
-#else /* ! HAVE_POLL */
-
-  fd_set read_set, write_set, err_set;
-  int max_fd = 0;
-  int i;
-  struct timeval tv;
-  int ready;
-  
-  FD_ZERO (&read_set);
-  FD_ZERO (&write_set);
-  FD_ZERO (&err_set);
-
-  for (i = 0; i < n_fds; i++)
-    {
-      DBusPollFD f = fds[i];
-
-      if (f.events & _DBUS_POLLIN)
-       FD_SET (f.fd, &read_set);
-
-      if (f.events & _DBUS_POLLOUT)
-       FD_SET (f.fd, &write_set);
-
-      FD_SET (f.fd, &err_set);
-
-      max_fd = MAX (max_fd, f.fd);
-    }
-    
-  tv.tv_sec = timeout_milliseconds / 1000;
-  tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
-
-  ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
-
-  if (ready > 0)
-    {
-      for (i = 0; i < n_fds; i++)
-       {
-         DBusPollFD f = fds[i];
-
-         f.revents = 0;
-
-         if (FD_ISSET (f.fd, &read_set))
-           f.revents |= _DBUS_POLLIN;
-
-         if (FD_ISSET (f.fd, &write_set))
-           f.revents |= _DBUS_POLLOUT;
-
-         if (FD_ISSET (f.fd, &err_set))
-           f.revents |= _DBUS_POLLERR;
-       }
-    }
-
-  return ready;
-#endif
-}
-
-/** nanoseconds in a second */
-#define NANOSECONDS_PER_SECOND       1000000000
-/** microseconds in a second */
-#define MICROSECONDS_PER_SECOND      1000000
-/** milliseconds in a second */
-#define MILLISECONDS_PER_SECOND      1000
-/** nanoseconds in a millisecond */
-#define NANOSECONDS_PER_MILLISECOND  1000000
-/** microseconds in a millisecond */
-#define MICROSECONDS_PER_MILLISECOND 1000
-
-/**
- * Sleeps the given number of milliseconds.
- * @param milliseconds number of milliseconds
- */
-void
-_dbus_sleep_milliseconds (int milliseconds)
-{
-#ifdef HAVE_NANOSLEEP
-  struct timespec req;
-  struct timespec rem;
-
-  req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
-  req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
-  rem.tv_sec = 0;
-  rem.tv_nsec = 0;
-
-  while (nanosleep (&req, &rem) < 0 && errno == EINTR)
-    req = rem;
-#elif defined (HAVE_USLEEP)
-  usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
-#else /* ! HAVE_USLEEP */
-  sleep (MAX (milliseconds / 1000, 1));
-#endif
-}
-
-/**
- * Get current time, as in gettimeofday().
- *
- * @param tv_sec return location for number of seconds
- * @param tv_usec return location for number of microseconds (thousandths)
- */
-void
-_dbus_get_current_time (long *tv_sec,
-                        long *tv_usec)
-{
-  struct timeval t;
-
-  gettimeofday (&t, NULL);
-
-  if (tv_sec)
-    *tv_sec = t.tv_sec;
-  if (tv_usec)
-    *tv_usec = t.tv_usec;
-}
-
-/**
- * Appends the contents of the given file to the string,
- * returning error code. At the moment, won't open a file
- * more than a megabyte in size.
- *
- * @param str the string to append to
- * @param filename filename to load
- * @param error place to set an error
- * @returns #FALSE if error was set
- */
-dbus_bool_t
-_dbus_file_get_contents (DBusString       *str,
-                         const DBusString *filename,
-                         DBusError        *error)
-{
-  int fd;
-  struct stat sb;
-  int orig_len;
-  int total;
-  const char *filename_c;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  filename_c = _dbus_string_get_const_data (filename);
-  
-  /* O_BINARY useful on Cygwin */
-  fd = open (filename_c, O_RDONLY | O_BINARY);
-  if (fd < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "%s", _dbus_strerror (errno));
-      return FALSE;
-    }
-
-  if (fstat (fd, &sb) < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "%s", _dbus_strerror (errno));
-
-      _dbus_verbose ("fstat() failed: %s",
-                     _dbus_strerror (errno));
-      
-      close (fd);
-      
-      return FALSE;
-    }
-
-  if (sb.st_size > _DBUS_ONE_MEGABYTE)
-    {
-      dbus_set_error (error, DBUS_ERROR_FAILED,
-                      "File size %lu is too large.\n",
-                     (unsigned long) sb.st_size);
-      close (fd);
-      return FALSE;
-    }
-  
-  total = 0;
-  orig_len = _dbus_string_get_length (str);
-  if (sb.st_size > 0 && S_ISREG (sb.st_mode))
-    {
-      int bytes_read;
-
-      while (total < (int) sb.st_size)
-        {
-          bytes_read = _dbus_read (fd, str,
-                                   sb.st_size - total);
-          if (bytes_read <= 0)
-            {
-              dbus_set_error (error, _dbus_error_from_errno (errno),
-                              "%s", _dbus_strerror (errno));
-
-              _dbus_verbose ("read() failed: %s",
-                             _dbus_strerror (errno));
-              
-              close (fd);
-              _dbus_string_set_length (str, orig_len);
-              return FALSE;
-            }
-          else
-            total += bytes_read;
-        }
-
-      close (fd);
-      return TRUE;
-    }
-  else if (sb.st_size != 0)
-    {
-      _dbus_verbose ("Can only open regular files at the moment.\n");
-      dbus_set_error (error, DBUS_ERROR_FAILED,
-                      "Not a regular file");
-      close (fd);
-      return FALSE;
-    }
-  else
-    {
-      close (fd);
-      return TRUE;
-    }
-}
-
+#ifdef DBUS_BUILD_TESTS
 static dbus_bool_t
-append_unique_chars (DBusString *str)
-{
-  static const char letters[] =
-    "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
-  int i;
-  int len;
-
-#define N_UNIQUE_CHARS 8
-  
-  if (!_dbus_generate_random_bytes (str, N_UNIQUE_CHARS))
-    return FALSE;
-  
-  len = _dbus_string_get_length (str);
-  i = len - N_UNIQUE_CHARS;
-  while (i < len)
-    {
-      _dbus_string_set_byte (str, i,
-                             letters[_dbus_string_get_byte (str, i) %
-                                     (sizeof (letters) - 1)]);
-
-      ++i;
-    }
-
-  _dbus_assert (_dbus_string_validate_ascii (str, len - N_UNIQUE_CHARS,
-                                             N_UNIQUE_CHARS));
-
-  return TRUE;
-}
-
-/**
- * Writes a string out to a file. If the file exists,
- * it will be atomically overwritten by the new data.
- *
- * @param str the string to write out
- * @param filename the file to save string to
- * @param error error to be filled in on failure
- * @returns #FALSE on failure
- */
-dbus_bool_t
-_dbus_string_save_to_file (const DBusString *str,
-                           const DBusString *filename,
-                           DBusError        *error)
-{
-  int fd;
-  int bytes_to_write;
-  const char *filename_c;
-  DBusString tmp_filename;
-  const char *tmp_filename_c;
-  int total;
-  dbus_bool_t need_unlink;
-  dbus_bool_t retval;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  fd = -1;
-  retval = FALSE;
-  need_unlink = FALSE;
-  
-  if (!_dbus_string_init (&tmp_filename))
-    {
-      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
-      return FALSE;
-    }
-
-  if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
-    {
-      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
-      return FALSE;
-    }
-  
-  if (!_dbus_string_append (&tmp_filename, "."))
-    {
-      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
-      return FALSE;
-    }
-  
-  if (!append_unique_chars (&tmp_filename))
-    {
-      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
-      return FALSE;
-    }
-    
-  filename_c = _dbus_string_get_const_data (filename);
-  tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
-
-  fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
-             0600);
-  if (fd < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Could not create %s: %s", tmp_filename_c,
-                      _dbus_strerror (errno));
-      goto out;
-    }
-
-  need_unlink = TRUE;
-  
-  total = 0;
-  bytes_to_write = _dbus_string_get_length (str);
-
-  while (total < bytes_to_write)
-    {
-      int bytes_written;
-
-      bytes_written = _dbus_write (fd, str, total,
-                                   bytes_to_write - total);
-
-      if (bytes_written <= 0)
-        {
-          dbus_set_error (error, _dbus_error_from_errno (errno),
-                          "Could not write to %s: %s", tmp_filename_c,
-                          _dbus_strerror (errno));
-          
-          goto out;
-        }
-
-      total += bytes_written;
-    }
-
-  if (close (fd) < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Could not close file %s: %s",
-                      tmp_filename_c, _dbus_strerror (errno));
-
-      goto out;
-    }
-
-  fd = -1;
-  
-  if (rename (tmp_filename_c, filename_c) < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Could not rename %s to %s: %s",
-                      tmp_filename_c, filename_c,
-                      _dbus_strerror (errno));
-
-      goto out;
-    }
-
-  need_unlink = FALSE;
-  
-  retval = TRUE;
-  
- out:
-  /* close first, then unlink, to prevent ".nfs34234235" garbage
-   * files
-   */
-
-  if (fd >= 0)
-    close (fd);
-        
-  if (need_unlink && unlink (tmp_filename_c) < 0)
-    _dbus_verbose ("Failed to unlink temp file %s: %s\n",
-                   tmp_filename_c, _dbus_strerror (errno));
-
-  _dbus_string_free (&tmp_filename);
-
-  if (!retval)
-    _DBUS_ASSERT_ERROR_IS_SET (error);
-  
-  return retval;
-}
-
-/** Creates the given file, failing if the file already exists.
- *
- * @param filename the filename
- * @param error error location
- * @returns #TRUE if we created the file and it didn't exist
- */
-dbus_bool_t
-_dbus_create_file_exclusively (const DBusString *filename,
-                               DBusError        *error)
-{
-  int fd;
-  const char *filename_c;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  filename_c = _dbus_string_get_const_data (filename);
-  
-  fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
-             0600);
-  if (fd < 0)
-    {
-      dbus_set_error (error,
-                      DBUS_ERROR_FAILED,
-                      "Could not create file %s: %s\n",
-                      filename_c,
-                      _dbus_errno_to_string (errno));
-      return FALSE;
-    }
-
-  if (close (fd) < 0)
-    {
-      dbus_set_error (error,
-                      DBUS_ERROR_FAILED,
-                      "Could not close file %s: %s\n",
-                      filename_c,
-                      _dbus_errno_to_string (errno));
-      return FALSE;
-    }
-  
-  return TRUE;
-}
-
-/**
- * Deletes the given file.
- *
- * @param filename the filename
- * @param error error location
- * 
- * @returns #TRUE if unlink() succeeded
- */
-dbus_bool_t
-_dbus_delete_file (const DBusString *filename,
-                   DBusError        *error)
-{
-  const char *filename_c;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  filename_c = _dbus_string_get_const_data (filename);
-
-  if (unlink (filename_c) < 0)
-    {
-      dbus_set_error (error, DBUS_ERROR_FAILED,
-                      "Failed to delete file %s: %s\n",
-                      filename_c, _dbus_strerror (errno));
-      return FALSE;
-    }
-  else
-    return TRUE;
-}
-
-/**
- * Creates a directory; succeeds if the directory
- * is created or already existed.
- *
- * @param filename directory filename
- * @param error initialized error object
- * @returns #TRUE on success
- */
-dbus_bool_t
-_dbus_create_directory (const DBusString *filename,
-                        DBusError        *error)
-{
-  const char *filename_c;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  filename_c = _dbus_string_get_const_data (filename);
-
-  if (mkdir (filename_c, 0700) < 0)
-    {
-      if (errno == EEXIST)
-        return TRUE;
-      
-      dbus_set_error (error, DBUS_ERROR_FAILED,
-                      "Failed to create directory %s: %s\n",
-                      filename_c, _dbus_strerror (errno));
-      return FALSE;
-    }
-  else
-    return TRUE;
-}
-
-/**
- * Appends the given filename to the given directory.
- *
- * @param dir the directory name
- * @param next_component the filename
- * @returns #TRUE on success
- */
-dbus_bool_t
-_dbus_concat_dir_and_file (DBusString       *dir,
-                           const DBusString *next_component)
-{
-  dbus_bool_t dir_ends_in_slash;
-  dbus_bool_t file_starts_with_slash;
-
-  if (_dbus_string_get_length (dir) == 0 ||
-      _dbus_string_get_length (next_component) == 0)
-    return TRUE;
-  
-  dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
-                                                    _dbus_string_get_length (dir) - 1);
-
-  file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
-
-  if (dir_ends_in_slash && file_starts_with_slash)
-    {
-      _dbus_string_shorten (dir, 1);
-    }
-  else if (!(dir_ends_in_slash || file_starts_with_slash))
-    {
-      if (!_dbus_string_append_byte (dir, '/'))
-        return FALSE;
-    }
-
-  return _dbus_string_copy (next_component, 0, dir,
-                            _dbus_string_get_length (dir));
-}
-
-struct DBusDirIter
-{
-  DIR *d;
-  
-};
-
-/**
- * Open a directory to iterate over.
- *
- * @param filename the directory name
- * @param error exception return object or #NULL
- * @returns new iterator, or #NULL on error
- */
-DBusDirIter*
-_dbus_directory_open (const DBusString *filename,
-                      DBusError        *error)
-{
-  DIR *d;
-  DBusDirIter *iter;
-  const char *filename_c;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  filename_c = _dbus_string_get_const_data (filename);
-
-  d = opendir (filename_c);
-  if (d == NULL)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "%s", _dbus_strerror (errno));
-      return NULL;
-    }
-  iter = dbus_new0 (DBusDirIter, 1);
-  if (iter == NULL)
-    {
-      closedir (d);
-      dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
-                      "Could not allocate memory for directory iterator");
-      return NULL;
-    }
-
-  iter->d = d;
-
-  return iter;
-}
-
-/**
- * Get next file in the directory. Will not return "." or ".."  on
- * UNIX. If an error occurs, the contents of "filename" are
- * undefined. The error is never set if the function succeeds.
- *
- * @todo for thread safety, I think we have to use
- * readdir_r(). (GLib has the same issue, should file a bug.)
- *
- * @param iter the iterator
- * @param filename string to be set to the next file in the dir
- * @param error return location for error
- * @returns #TRUE if filename was filled in with a new filename
- */
-dbus_bool_t
-_dbus_directory_get_next_file (DBusDirIter      *iter,
-                               DBusString       *filename,
-                               DBusError        *error)
-{
-  struct dirent *ent;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
- again:
-  errno = 0;
-  ent = readdir (iter->d);
-  if (ent == NULL)
-    {
-      if (errno != 0)
-        dbus_set_error (error,
-                        _dbus_error_from_errno (errno),
-                        "%s", _dbus_strerror (errno));
-      return FALSE;
-    }
-  else if (ent->d_name[0] == '.' &&
-           (ent->d_name[1] == '\0' ||
-            (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
-    goto again;
-  else
-    {
-      _dbus_string_set_length (filename, 0);
-      if (!_dbus_string_append (filename, ent->d_name))
-        {
-          dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
-                          "No memory to read directory entry");
-          return FALSE;
-        }
-      else
-        return TRUE;
-    }
-}
-
-/**
- * Closes a directory iteration.
- */
-void
-_dbus_directory_close (DBusDirIter *iter)
-{
-  closedir (iter->d);
-  dbus_free (iter);
-}
-
-/**
- * Generates the given number of random bytes,
- * using the best mechanism we can come up with.
- *
- * @param str the string
- * @param n_bytes the number of random bytes to append to string
- * @returns #TRUE on success, #FALSE if no memory or other failure
- */
-dbus_bool_t
-_dbus_generate_random_bytes (DBusString *str,
-                             int         n_bytes)
+ascii_isspace (char c)
 {
-  int old_len;
-  int fd;
-  
-  old_len = _dbus_string_get_length (str);
-  fd = -1;
-
-  /* note, urandom on linux will fall back to pseudorandom */
-  fd = open ("/dev/urandom", O_RDONLY);
-  if (fd < 0)
-    {
-      unsigned long tv_usec;
-      int i;
-
-      /* fall back to pseudorandom */
-      _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
-                     n_bytes);
-      
-      _dbus_get_current_time (NULL, &tv_usec);
-      srand (tv_usec);
-      
-      i = 0;
-      while (i < n_bytes)
-        {
-          double r;
-          unsigned int b;
-          
-          r = rand ();
-          b = (r / (double) RAND_MAX) * 255.0;
-          
-          if (!_dbus_string_append_byte (str, b))
-            goto failed;
-          
-          ++i;
-        }
-
-      return TRUE;
-    }
-  else
-    {
-      if (_dbus_read (fd, str, n_bytes) != n_bytes)
-        goto failed;
-
-      _dbus_verbose ("Read %d bytes from /dev/urandom\n",
-                     n_bytes);
-      
-      close (fd);
-
-      return TRUE;
-    }
-
- failed:
-  _dbus_string_set_length (str, old_len);
-  if (fd >= 0)
-    close (fd);
-  return FALSE;
+  return (c == ' ' ||
+         c == '\f' ||
+         c == '\n' ||
+         c == '\r' ||
+         c == '\t' ||
+         c == '\v');
 }
+#endif /* DBUS_BUILD_TESTS */
 
-/**
- * A wrapper around strerror()
- *
- * @todo get rid of this function, it's the same as
- * _dbus_strerror().
- * 
- * @param errnum the errno
- * @returns an error message (never #NULL)
- */
-const char *
-_dbus_errno_to_string (int errnum)
+#ifdef DBUS_BUILD_TESTS
+static dbus_bool_t
+ascii_isdigit (char c)
 {
-  const char *msg;
-  
-  msg = strerror (errnum);
-  if (msg == NULL)
-    msg = "unknown";
+  return c >= '0' && c <= '9';
+}
+#endif /* DBUS_BUILD_TESTS */
 
-  return msg;
+#ifdef DBUS_BUILD_TESTS
+static dbus_bool_t
+ascii_isxdigit (char c)
+{
+  return (ascii_isdigit (c) ||
+         (c >= 'a' && c <= 'f') ||
+         (c >= 'A' && c <= 'F'));
 }
+#endif /* DBUS_BUILD_TESTS */
 
-/**
- * A wrapper around strerror() because some platforms
- * may be lame and not have strerror().
+#ifdef DBUS_BUILD_TESTS
+/* Calls strtod in a locale-independent fashion, by looking at
+ * the locale data and patching the decimal comma to a point.
  *
- * @param error_number errno.
- * @returns error description.
+ * Relicensed from glib.
  */
-const char*
-_dbus_strerror (int error_number)
+static double
+ascii_strtod (const char *nptr,
+             char      **endptr)
 {
-  const char *msg;
-  
-  msg = strerror (error_number);
-  if (msg == NULL)
-    msg = "unknown";
+  /* FIXME: The Win32 C library's strtod() doesn't handle hex.
+   * Presumably many Unixes don't either.
+   */
 
-  return msg;
-}
+  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 */
 
-/* Avoids a danger in threaded situations (calling close()
- * on a file descriptor twice, and another thread has
- * re-opened it since the first close)
- */
-static int
-close_and_invalidate (int *fd)
-{
-  int ret;
+  fail_pos = NULL;
 
-  if (*fd < 0)
-    return -1;
-  else
+  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)
     {
-      ret = close (*fd);
-      *fd = -1;
+      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 */
     }
 
-  return ret;
-}
-
-static dbus_bool_t
-make_pipe (int        p[2],
-           DBusError *error)
-{
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+  /* Set errno to zero, so that we can distinguish zero results
+     and underflows */
+  errno = 0;
   
-  if (pipe (p) < 0)
+  if (decimal_point_pos)
     {
-      dbus_set_error (error,
-                     DBUS_ERROR_SPAWN_FAILED,
-                     "Failed to create pipe for communicating with child process (%s)",
-                     _dbus_errno_to_string (errno));
-      return FALSE;
+      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
-    {
-      _dbus_fd_set_close_on_exec (p[0]);
-      _dbus_fd_set_close_on_exec (p[1]);      
-      return TRUE;
-    }
-}
+    val = strtod (nptr, &fail_pos);
 
-enum
-{
-  CHILD_CHDIR_FAILED,
-  CHILD_EXEC_FAILED,
-  CHILD_DUP2_FAILED,
-  CHILD_FORK_FAILED
-};
-
-static void
-write_err_and_exit (int fd, int msg)
-{
-  int en = errno;
+  if (endptr)
+    *endptr = fail_pos;
   
-  write (fd, &msg, sizeof(msg));
-  write (fd, &en, sizeof(en));
-  
-  _exit (1);
+  return val;
 }
+#endif /* DBUS_BUILD_TESTS */
 
-static dbus_bool_t
-read_ints (int        fd,
-          int       *buf,
-          int        n_ints_in_buf,
-          int       *n_ints_read,
-          DBusError *error)
+#ifdef DBUS_BUILD_TESTS
+/**
+ * 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)
 {
-  size_t bytes = 0;    
+  double v;
+  const char *p;
+  char *end;
 
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  while (TRUE)
-    {
-      size_t chunk;    
+  p = _dbus_string_get_const_data_len (str, start,
+                                       _dbus_string_get_length (str) - start);
 
-      if (bytes >= sizeof(int)*2)
-        break; /* give up, who knows what happened, should not be
-                * possible.
-                */
-          
-    again:
-      chunk = read (fd,
-                    ((char*)buf) + bytes,
-                    sizeof(int) * n_ints_in_buf - bytes);
-      if (chunk < 0 && errno == EINTR)
-        goto again;
-          
-      if (chunk < 0)
-        {
-          /* Some weird shit happened, bail out */
-              
-          dbus_set_error (error,
-                         DBUS_ERROR_SPAWN_FAILED,
-                         "Failed to read from child pipe (%s)",
-                         _dbus_errno_to_string (errno));
-
-          return FALSE;
-        }
-      else if (chunk == 0)
-        break; /* EOF */
-      else /* chunk > 0 */
-       bytes += chunk;
-    }
+  /* parsing hex works on linux but isn't portable, so intercept it
+   * here to get uniform behavior.
+   */
+  if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
+    return FALSE;
+  
+  end = NULL;
+  errno = 0;
+  v = ascii_strtod (p, &end);
+  if (end == NULL || end == p || errno != 0)
+    return FALSE;
 
-  *n_ints_read = (int)(bytes / sizeof(int));
+  if (value_return)
+    *value_return = v;
+  if (end_return)
+    *end_return = start + (end - p);
 
   return TRUE;
 }
+#endif /* DBUS_BUILD_TESTS */
 
-static void
-do_exec (int                       child_err_report_fd,
-        char                    **argv,
-        DBusSpawnChildSetupFunc   child_setup,
-        void                     *user_data)
-{
-#ifdef DBUS_BUILD_TESTS
-  int i, max_open;
-#endif
+/** @} */ /* DBusString group */
 
-  if (child_setup)
-    (* child_setup) (user_data);
+/**
+ * @addtogroup DBusInternalsUtils
+ * @{
+ */
 
-#ifdef DBUS_BUILD_TESTS
-  max_open = sysconf (_SC_OPEN_MAX);
+void
+_dbus_generate_pseudorandom_bytes_buffer (char *buffer,
+                                          int   n_bytes)
+{
+  long tv_usec;
+  int i;
+  
+  /* fall back to pseudorandom */
+  _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
+                 n_bytes);
   
-  for (i = 3; i < max_open; i++)
+  _dbus_get_current_time (NULL, &tv_usec);
+  srand (tv_usec);
+  
+  i = 0;
+  while (i < n_bytes)
     {
-      int retval;
+      double r;
+      unsigned int b;
+          
+      r = rand ();
+      b = (r / (double) RAND_MAX) * 255.0;
 
-      retval = fcntl (i, F_GETFD);
+      buffer[i] = b;
 
-      if (retval != -1 && !(retval & FD_CLOEXEC))
-       _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
+      ++i;
     }
-#endif
-  
-  execv (argv[0], argv);
-
-  /* Exec failed */
-  write_err_and_exit (child_err_report_fd,
-                      CHILD_EXEC_FAILED);
-  
 }
 
 /**
- * Spawns a new process. The executable name and argv[0]
- * are the same, both are provided in argv[0]. The child_setup
- * function is passed the given user_data and is run in the child
- * just before calling exec().
+ * Fills n_bytes of the given buffer with random bytes.
  *
- * @todo this code should be reviewed/double-checked as it's fairly
- * complex and no one has reviewed it yet.
- *
- * @param argv the executable and arguments
- * @param child_setup function to call in child pre-exec()
- * @param user_data user data for setup function
- * @param error error object to be filled in if function fails
- * @returns #TRUE on success, #FALSE if error is filled in
+ * @param buffer an allocated buffer
+ * @param n_bytes the number of bytes in buffer to write to
  */
-dbus_bool_t
-_dbus_spawn_async (char                    **argv,
-                  DBusSpawnChildSetupFunc   child_setup,
-                  void                     *user_data,
-                  DBusError                *error)
+void
+_dbus_generate_random_bytes_buffer (char *buffer,
+                                    int   n_bytes)
 {
-  int pid = -1, grandchild_pid;
-  int child_err_report_pipe[2] = { -1, -1 };
-  int status;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  if (!make_pipe (child_err_report_pipe, error))
-    return FALSE;
-
-  pid = fork ();
-  
-  if (pid < 0)
-    {
-      dbus_set_error (error,
-                     DBUS_ERROR_SPAWN_FORK_FAILED,
-                     "Failed to fork (%s)",
-                     _dbus_errno_to_string (errno));
-      return FALSE;
-    }
-  else if (pid == 0)
-    {
-      /* Immediate child. */
-      
-      /* Be sure we crash if the parent exits
-       * and we write to the err_report_pipe
-       */
-      signal (SIGPIPE, SIG_DFL);
-
-      /* Close the parent's end of the pipes;
-       * not needed in the close_descriptors case,
-       * though
-       */
-      close_and_invalidate (&child_err_report_pipe[0]);
+  DBusString str;
 
-      /* We need to fork an intermediate child that launches the
-       * final child. The purpose of the intermediate child
-       * is to exit, so we can waitpid() it immediately.
-       * Then the grandchild will not become a zombie.
-       */
-      grandchild_pid = fork ();
-      
-      if (grandchild_pid < 0)
-       {
-         write_err_and_exit (child_err_report_pipe[1],
-                             CHILD_FORK_FAILED);              
-       }
-      else if (grandchild_pid == 0)
-       {
-         do_exec (child_err_report_pipe[1],
-                  argv,
-                  child_setup, user_data);
-       }
-      else
-       {
-         _exit (0);
-       }
-    }
-  else
+  if (!_dbus_string_init (&str))
     {
-      /* Parent */
-
-      int buf[2];
-      int n_ints = 0;    
-      
-      /* Close the uncared-about ends of the pipes */
-      close_and_invalidate (&child_err_report_pipe[1]);
-
-    wait_again:
-      if (waitpid (pid, &status, 0) < 0)
-       {
-         if (errno == EINTR)
-           goto wait_again;
-         else if (errno == ECHILD)
-           ; /* do nothing, child already reaped */
-         else
-           _dbus_warn ("waitpid() should not fail in "
-                       "'_dbus_spawn_async'");
-       }
-
-      if (!read_ints (child_err_report_pipe[0],
-                      buf, 2, &n_ints,
-                      error))
-         goto cleanup_and_fail;
-      
-      if (n_ints >= 2)
-        {
-          /* Error from the child. */
-          switch (buf[0])
-            {
-           default:
-              dbus_set_error (error,
-                             DBUS_ERROR_SPAWN_FAILED,
-                             "Unknown error executing child process \"%s\"",
-                             argv[0]);
-              break;
-           }
-
-         goto cleanup_and_fail;
-       }
-
-
-      /* Success against all odds! return the information */
-      close_and_invalidate (&child_err_report_pipe[0]);
-
-      return TRUE;
+      _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
+      return;
     }
 
- cleanup_and_fail:
-
-  /* There was an error from the Child, reap the child to avoid it being
-     a zombie.
-  */
-  if (pid > 0)
+  if (!_dbus_generate_random_bytes (&str, n_bytes))
     {
-    wait_failed:
-      if (waitpid (pid, NULL, 0) < 0)
-       {
-          if (errno == EINTR)
-            goto wait_failed;
-          else if (errno == ECHILD)
-            ; /* do nothing, child already reaped */
-          else
-            _dbus_warn ("waitpid() should not fail in "
-                       "'_dbus_spawn_async'");
-       }
+      _dbus_string_free (&str);
+      _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
+      return;
     }
-  
-  close_and_invalidate (&child_err_report_pipe[0]);
-  close_and_invalidate (&child_err_report_pipe[1]);
 
-  return FALSE;
-}
+  _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
 
-/**
- * signal (SIGPIPE, SIG_IGN);
- */
-void
-_dbus_disable_sigpipe (void)
-{
-  signal (SIGPIPE, SIG_IGN);
+  _dbus_string_free (&str);
 }
 
 /**
- * Sets the file descriptor to be close
- * on exec. Should be called for all file
- * descriptors in D-BUS code.
+ * Generates the given number of random bytes, where the bytes are
+ * chosen from the alphanumeric ASCII subset.
  *
- * @param fd the file descriptor
+ * @param str the string
+ * @param n_bytes the number of random ASCII bytes to append to string
+ * @returns #TRUE on success, #FALSE if no memory or other failure
  */
-void
-_dbus_fd_set_close_on_exec (int fd)
+dbus_bool_t
+_dbus_generate_random_ascii (DBusString *str,
+                             int         n_bytes)
 {
-  int val;
+  static const char letters[] =
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
+  int i;
+  int len;
   
-  val = fcntl (fd, F_GETFD, 0);
+  if (!_dbus_generate_random_bytes (str, n_bytes))
+    return FALSE;
   
-  if (val < 0)
-    return;
+  len = _dbus_string_get_length (str);
+  i = len - n_bytes;
+  while (i < len)
+    {
+      _dbus_string_set_byte (str, i,
+                             letters[_dbus_string_get_byte (str, i) %
+                                     (sizeof (letters) - 1)]);
 
-  val |= FD_CLOEXEC;
-  
-  fcntl (fd, F_SETFD, val);
+      ++i;
+    }
+
+  _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
+                                             n_bytes));
+
+  return TRUE;
 }
 
 /**
- * Converts a UNIX errno into a #DBusError name.
+ * Converts a UNIX or Windows errno
+ * into a #DBusError name.
  *
  * @todo should cover more errnos, specifically those
  * from open().
@@ -2854,7 +962,7 @@ _dbus_error_from_errno (int error_number)
 #endif
 #ifdef EEXIST
     case EEXIST:
-      return DBUS_ERROR_FILE_NOT_FOUND;
+      return DBUS_ERROR_FILE_EXISTS;
 #endif
 #ifdef ENOENT
     case ENOENT:
@@ -2866,201 +974,54 @@ _dbus_error_from_errno (int error_number)
 }
 
 /**
- * Exit the process, returning the given value.
- *
- * @param code the exit code
+ * Assign 0 to the global errno variable
  */
 void
-_dbus_exit (int code)
-{
-  _exit (code);
-}
-
-/**
- * stat() wrapper.
- *
- * @param filename the filename to stat
- * @param statbuf the stat info to fill in
- * @param error return location for error
- * @returns #FALSE if error was set
- */
-dbus_bool_t
-_dbus_stat (const DBusString *filename,
-            DBusStat         *statbuf,
-            DBusError        *error)
+_dbus_set_errno_to_zero (void)
 {
-  const char *filename_c;
-  struct stat sb;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  filename_c = _dbus_string_get_const_data (filename);
-
-  if (stat (filename_c, &sb) < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "%s", _dbus_strerror (errno));
-      return FALSE;
-    }
-
-  statbuf->mode = sb.st_mode;
-  statbuf->nlink = sb.st_nlink;
-  statbuf->uid = sb.st_uid;
-  statbuf->gid = sb.st_gid;
-  statbuf->size = sb.st_size;
-  statbuf->atime = sb.st_atime;
-  statbuf->mtime = sb.st_mtime;
-  statbuf->ctime = sb.st_ctime;
-
-  return TRUE;
+  errno = 0;
 }
 
 /**
- * Creates a full-duplex pipe (as in socketpair()).
- * Sets both ends of the pipe nonblocking.
- *
- * @param fd1 return location for one end
- * @param fd2 return location for the other end
- * @param error error return
- * @returns #FALSE on failure (if error is set)
+ * See if errno is set
+ * @returns #TRUE if errno is not 0
  */
 dbus_bool_t
-_dbus_full_duplex_pipe (int       *fd1,
-                        int       *fd2,
-                        DBusError *error)
+_dbus_get_is_errno_nonzero (void)
 {
-#ifdef HAVE_SOCKETPAIR
-  int fds[2];
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Could not create full-duplex pipe");
-      return FALSE;
-    }
-
-  if (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
-      !_dbus_set_fd_nonblocking (fds[1], NULL))
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Could not set full-duplex pipe nonblocking");
-      
-      close (fds[0]);
-      close (fds[1]);
-      
-      return FALSE;
-    }
-  
-  *fd1 = fds[0];
-  *fd2 = fds[1];
-  
-  return TRUE;  
-#else
-  _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
-  dbus_set_error (error, DBUS_ERROR_FAILED,
-                  "_dbus_full_duplex_pipe() not implemented on this OS");
-  return FALSE;
-#endif
+  return errno != 0;
 }
 
 /**
- * Closes a file descriptor.
- *
- * @param fd the file descriptor
- * @param error error object
- * @returns #FALSE if error set
+ * See if errno is ENOMEM
+ * @returns #TRUE if errno == ENOMEM
  */
 dbus_bool_t
-_dbus_close (int        fd,
-             DBusError *error)
+_dbus_get_is_errno_enomem (void)
 {
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
- again:
-  if (close (fd) < 0)
-    {
-      if (errno == EINTR)
-        goto again;
-
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Could not close fd %d", fd);
-      return FALSE;
-    }
-
-  return TRUE;
+  return errno == ENOMEM;
 }
 
 /**
- * Sets a file descriptor to be nonblocking.
- *
- * @param fd the file descriptor.
- * @param error address of error location.
- * @returns #TRUE on success.
+ * See if errno is EINTR
+ * @returns #TRUE if errno == EINTR
  */
 dbus_bool_t
-_dbus_set_fd_nonblocking (int             fd,
-                          DBusError      *error)
+_dbus_get_is_errno_eintr (void)
 {
-  int val;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-  
-  val = fcntl (fd, F_GETFL, 0);
-  if (val < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to get flags from file descriptor %d: %s",
-                      fd, _dbus_strerror (errno));
-      _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
-                     _dbus_strerror (errno));
-      return FALSE;
-    }
-
-  if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to set nonblocking flag of file descriptor %d: %s",
-                      fd, _dbus_strerror (errno));
-      _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
-                     fd, _dbus_strerror (errno));
-
-      return FALSE;
-    }
-
-  return TRUE;
+  return errno == EINTR;
 }
 
 /**
- * On GNU libc systems, print a crude backtrace to the verbose log.
- * On other systems, print "no backtrace support"
- *
+ * Get error message from errno
+ * @returns _dbus_strerror(errno)
  */
-void
-_dbus_print_backtrace (void)
+const char*
+_dbus_strerror_from_errno (void)
 {
-#if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
-  void *bt[500];
-  int bt_size;
-  int i;
-  char **syms;
-  
-  bt_size = backtrace (bt, 500);
-
-  syms = backtrace_symbols (bt, bt_size);
-  
-  i = 0;
-  while (i < bt_size)
-    {
-      _dbus_verbose ("  %s\n", syms[i]);
-      ++i;
-    }
-
-  free (syms);
-#else
-  _dbus_verbose ("  D-BUS not compiled with backtrace support\n");
-#endif
+  return _dbus_strerror (errno);
 }
 
 /** @} end of sysdeps */
+
+/* tests in dbus-sysdeps-util.c */