Revert "Remove refcounting from DBusAuth and DBusAuthorization"
[platform/upstream/dbus.git] / dbus / dbus-sysdeps-win.c
index ece53a0..38758bd 100644 (file)
@@ -1,12 +1,12 @@
-/* -*- mode: C; c-file-style: "gnu" -*- */
+/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
  * 
  * Copyright (C) 2002, 2003  Red Hat, Inc.
  * Copyright (C) 2003 CodeFactory AB
  * Copyright (C) 2005 Novell, Inc.
- * Copyright (C) 2006 Ralf Habacker <ralf.habacker@freenet.de>
- * Copyright (C) 2006 Peter Kümmel  <syntheticpp@gmx.net>
+ * Copyright (C) 2006 Peter Kümmel  <syntheticpp@gmx.net>
  * Copyright (C) 2006 Christian Ehrlicher <ch.ehrlicher@gmx.de>
+ * Copyright (C) 2006-2013 Ralf Habacker <ralf.habacker@freenet.de>
  *
  * Licensed under the Academic Free License version 2.1
  * 
  * 
  * 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
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
  *
  */
 
-/* #define ENABLE_DBUSUSERINFO */
-
-struct DBusCredentials{
-    int uid;
-    int gid;
-    int pid;
-};
-
-#undef open
+#include <config.h>
 
 #define STRSAFE_NO_DEPRECATE
 
 #ifndef DBUS_WINCE
-#define _WIN32_WINNT 0x0500
+#ifndef _WIN32_WINNT
+#define _WIN32_WINNT 0x0501
+#endif
 #endif
 
 #include "dbus-internals.h"
+#include "dbus-sha.h"
 #include "dbus-sysdeps.h"
 #include "dbus-threads.h"
 #include "dbus-protocol.h"
 #include "dbus-string.h"
+#include "dbus-sysdeps.h"
 #include "dbus-sysdeps-win.h"
 #include "dbus-protocol.h"
 #include "dbus-hash.h"
 #include "dbus-sockets-win.h"
 #include "dbus-list.h"
+#include "dbus-nonce.h"
 #include "dbus-credentials.h"
 
 #include <windows.h>
-#include <fcntl.h>
+#include <ws2tcpip.h>
+#include <wincrypt.h>
+#include <iphlpapi.h>
 
-#include <process.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-
-#ifndef O_BINARY
-#define O_BINARY 0
-#endif
+/* Declarations missing in mingw's and windows sdk 7.0 headers */
+extern BOOL WINAPI ConvertStringSidToSidA (LPCSTR  StringSid, PSID *Sid);
+extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
 
-#ifndef HAVE_SOCKLEN_T
-#define socklen_t int
-#endif
+#include <stdio.h>
 
-#ifdef ENABLE_DBUSSOCKET
-_DBUS_DEFINE_GLOBAL_LOCK (win_fds);
+#include <string.h>
+#if HAVE_ERRNO_H
+#include <errno.h>
 #endif
-
-#ifdef ENABLE_UID_TO_SID
-_DBUS_DEFINE_GLOBAL_LOCK (sid_atom_cache);
+#ifndef DBUS_WINCE
+#include <mbstring.h>
+#include <sys/stat.h>
+#include <sys/types.h>
 #endif
 
-#ifdef ENABLE_DBUSUSERINFO
-typedef struct {
-    int uid;
-    char *username;
-    int n_group_ids;
-    dbus_gid_t *group_ids;
-    int primary_gid;
-    char *homedir;
-} DBusUserInfo;
+#ifdef HAVE_WS2TCPIP_H
+/* getaddrinfo for Windows CE (and Windows).  */
+#include <ws2tcpip.h>
 #endif
 
-#ifdef ENABLE_DBUSSOCKET
-static
-void 
-_dbus_lock_sockets()
-{
-       _dbus_assert (win_fds!=0); 
-       _DBUS_LOCK   (win_fds);
-}
-
-static
-void 
-_dbus_unlock_sockets()
-{
-       _dbus_assert (win_fds!=0); 
-       _DBUS_UNLOCK (win_fds);
-}
+#ifdef HAVE_WSPIAPI_H
+// needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
+#ifdef __GNUC__
+#define _inline
+#include "wspiapi.h"
+#else
+#include <wspiapi.h>
 #endif
+#endif // HAVE_WSPIAPI_H
 
-#ifdef _DBUS_WIN_USE_RANDOMIZER
-static int  win_encap_randomizer;
+#ifndef O_BINARY
+#define O_BINARY 0
 #endif
 
-#ifdef ENABLE_UID_TO_SID
-static DBusHashTable *sid_atom_cache = NULL;
-#endif
+typedef int socklen_t;
 
-static DBusString dbusdir;
-static int working_dir_init = 0;
 
-int _dbus_init_working_dir(char *s)
+void
+_dbus_win_set_errno (int err)
 {
-  /* change working directory to one level above 
-     of dbus-daemon executable path.  
-     This allows the usage of relative path in 
-     config files or command line parameters */
-  DBusString daemon_path,bin_path;
-
-  if (!_dbus_string_init (&daemon_path))
-    return FALSE;
-  
-  if (!_dbus_string_init (&bin_path))
-    return FALSE;
-
-  if (!_dbus_string_init (&dbusdir))
-    return FALSE;
-  
-  _dbus_string_append(&daemon_path,s);
-  _dbus_string_get_dirname(&daemon_path,&bin_path);
-  _dbus_string_get_dirname(&bin_path,&dbusdir);
-  chdir(_dbus_string_get_const_data(&dbusdir));
-  _dbus_verbose ("Change working path to %s\n",_dbus_string_get_const_data (&dbusdir));
-  working_dir_init = 1;
-  return TRUE;
+#ifdef DBUS_WINCE
+  SetLastError (err);
+#else
+  errno = err;
+#endif
 }
 
-DBusString *_dbus_get_working_dir(void)
-{
-  if (!working_dir_init) 
-    return NULL;
-       
-  _dbus_verbose ("retrieving working path %s\n",_dbus_string_get_const_data (&dbusdir));
-  return &dbusdir;
-}
+static BOOL is_winxp_sp3_or_lower();
+
+/*
+ * _MIB_TCPROW_EX and friends are not available in system headers
+ *  and are mapped to attribute identical ...OWNER_PID typedefs.
+ */
+typedef MIB_TCPROW_OWNER_PID _MIB_TCPROW_EX;
+typedef MIB_TCPTABLE_OWNER_PID MIB_TCPTABLE_EX;
+typedef PMIB_TCPTABLE_OWNER_PID PMIB_TCPTABLE_EX;
+typedef DWORD (WINAPI *ProcAllocateAndGetTcpExtTableFromStack)(PMIB_TCPTABLE_EX*,BOOL,HANDLE,DWORD,DWORD);
+static ProcAllocateAndGetTcpExtTableFromStack lpfnAllocateAndGetTcpExTableFromStack = NULL;
 
 /**
- * File interface
- *
+ * AllocateAndGetTcpExTableFromStack() is undocumented and not exported,
+ * but is the only way to do this in older XP versions.
+ * @return true if the procedures could be loaded
  */
-dbus_bool_t
-_dbus_file_open (DBusFile   *file,
-                 const char *filename,
-                 int         oflag,
-                 int         pmode)
+static BOOL
+load_ex_ip_helper_procedures(void)
 {
-  if (pmode!=-1)
-    file->FDATA = _open (filename, oflag, pmode);
-  else
-    file->FDATA = _open (filename, oflag);
-  if (file->FDATA >= 0)
-    return TRUE;
-  else
+  HMODULE hModule = LoadLibrary ("iphlpapi.dll");
+  if (hModule == NULL)
     {
-      file->FDATA = -1;
+      _dbus_verbose ("could not load iphlpapi.dll\n");
       return FALSE;
     }
-}
-
-dbus_bool_t
-_dbus_file_close (DBusFile  *file,
-                  DBusError *error)
-{
-  const int fd = file->FDATA;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
 
-  _dbus_assert (fd >= 0);
-
-  if (_close (fd) == -1)
+  lpfnAllocateAndGetTcpExTableFromStack = (ProcAllocateAndGetTcpExtTableFromStack)GetProcAddress (hModule, "AllocateAndGetTcpExTableFromStack");
+  if (lpfnAllocateAndGetTcpExTableFromStack == NULL)
     {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Could not close fd %d: %s", fd,
-                      _dbus_strerror (errno));
+      _dbus_verbose ("could not find function AllocateAndGetTcpExTableFromStack in iphlpapi.dll\n");
       return FALSE;
     }
-
-  file->FDATA = -1;
-  _dbus_verbose ("closed C file descriptor %d:\n",fd);
-
   return TRUE;
 }
 
-int
-_dbus_file_read(DBusFile   *file,
-                DBusString *buffer,
-                int         count)
+/**
+ * get pid from localhost tcp connection using peer_port
+ * This function is available on WinXP >= SP3
+ * @param peer_port peers tcp port
+ * @return process id or 0 if connection has not been found
+ */
+static dbus_pid_t
+get_pid_from_extended_tcp_table(int peer_port)
 {
-  const int fd = file->FDATA;
-  int bytes_read;
-  int start;
-  char *data;
-  _dbus_assert (count >= 0);
-
-  start = _dbus_string_get_length (buffer);
+  dbus_pid_t result;
+  DWORD errorCode, size, i;
+  MIB_TCPTABLE_OWNER_PID *tcp_table;
 
-  if (!_dbus_string_lengthen (buffer, count))
+  if ((errorCode =
+       GetExtendedTcpTable (NULL, &size, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0)) == ERROR_INSUFFICIENT_BUFFER)
     {
-      errno = ENOMEM;
-      return -1;
+      tcp_table = (MIB_TCPTABLE_OWNER_PID *) dbus_malloc (size);
+      if (tcp_table == NULL)
+        {
+          _dbus_verbose ("Error allocating memory\n");
+          return 0;
+        }
     }
-
-  data = _dbus_string_get_data_len (buffer, start, count);
-
-  _dbus_assert (fd >= 0);
-
-  _dbus_verbose ("read: count=%d fd=%d\n", count, fd);
-  bytes_read = read (fd, data, count);
-
-  if (bytes_read == -1)
-    _dbus_verbose ("read: failed: %s\n", _dbus_strerror (errno));
   else
-    _dbus_verbose ("read: = %d\n", bytes_read);
-
-  if (bytes_read < 0)
     {
-      /* put length back (note that this doesn't actually realloc anything) */
-      _dbus_string_set_length (buffer, start);
-      return -1;
+      _dbus_verbose ("unexpected error returned from GetExtendedTcpTable %d\n", errorCode);
+      return 0;
     }
-  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;
+  if ((errorCode = GetExtendedTcpTable (tcp_table, &size, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0)) != NO_ERROR)
+    {
+      _dbus_verbose ("Error fetching tcp table %d\n", (int)errorCode);
+      dbus_free (tcp_table);
+      return 0;
     }
-}
 
-int
-_dbus_file_write (DBusFile         *file,
-                  const DBusString *buffer,
-                  int               start,
-                  int               len)
-{
-  const int fd = file->FDATA;
-  const char *data;
-  int bytes_written;
-
-  data = _dbus_string_get_const_data_len (buffer, start, len);
-
-  _dbus_assert (fd >= 0);
-
-  _dbus_verbose ("write: len=%d fd=%d\n", len, fd);
-  bytes_written = write (fd, data, len);
-
-  if (bytes_written == -1)
-    _dbus_verbose ("write: failed: %s\n", _dbus_strerror (errno));
-  else
-    _dbus_verbose ("write: = %d\n", bytes_written);
-
-#if 0
-
-  if (bytes_written > 0)
-    _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
-#endif
-
-  return bytes_written;
-}
-
-dbus_bool_t
-_dbus_is_valid_file (DBusFile* file)
-{
-  return file->FDATA >= 0;
-}
+  result = 0;
+  for (i = 0; i < tcp_table->dwNumEntries; i++)
+    {
+      MIB_TCPROW_OWNER_PID *p = &tcp_table->table[i];
+      int local_address = ntohl (p->dwLocalAddr);
+      int local_port = ntohs (p->dwLocalPort);
+      if (p->dwState == MIB_TCP_STATE_ESTAB
+          && local_address == INADDR_LOOPBACK && local_port == peer_port)
+         result = p->dwOwningPid;
+    }
 
-dbus_bool_t _dbus_fstat (DBusFile    *file,
-                         struct stat *sb)
-{
-  return fstat(file->FDATA, sb) >= 0;
+  dbus_free (tcp_table);
+  _dbus_verbose ("got pid %d\n", (int)result);
+  return result;
 }
 
 /**
- * write data to a pipe.
- *
- * @param pipe the pipe instance
- * @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
- * @param error error return
- * @returns the number of bytes written or -1 on error
+ * get pid from localhost tcp connection using peer_port
+ * This function is available on all WinXP versions, but
+ * not in wine (at least version <= 1.6.0)
+ * @param peer_port peers tcp port
+ * @return process id or 0 if connection has not been found
  */
-int
-_dbus_pipe_write (DBusPipe         *pipe,
-                  const DBusString *buffer,
-                  int               start,
-                  int               len,
-                  DBusError        *error)
+static dbus_pid_t
+get_pid_from_tcp_ex_table(int peer_port)
 {
-  int written;
-  DBusFile file;
-  file.FDATA = pipe->fd_or_handle;
-  written = _dbus_file_write (&file, buffer, start, len);
-  if (written < 0)
+  dbus_pid_t result;
+  DWORD errorCode, i;
+  PMIB_TCPTABLE_EX tcp_table = NULL;
+
+  if (!load_ex_ip_helper_procedures ())
     {
-      dbus_set_error (error, DBUS_ERROR_FAILED,
-                      "Writing to pipe: %s\n",
-                      _dbus_strerror (errno));
+      _dbus_verbose
+        ("Error not been able to load iphelper procedures\n");
+      return 0;
     }
-  return written;
-}
 
-/**
- * close a pipe.
- *
- * @param pipe the pipe instance
- * @param error return location for an error
- * @returns #FALSE if error is set
- */
-int
-_dbus_pipe_close  (DBusPipe         *pipe,
-                   DBusError        *error)
-{
-  DBusFile file;
-  file.FDATA = pipe->fd_or_handle;
-  if (_dbus_file_close (&file, error) < 0)
+  errorCode = lpfnAllocateAndGetTcpExTableFromStack (&tcp_table, TRUE, GetProcessHeap(), 0, 2);
+
+  if (errorCode != NO_ERROR)
     {
-      return -1;
+      _dbus_verbose
+        ("Error not been able to call AllocateAndGetTcpExTableFromStack()\n");
+      return 0;
     }
-  else
+
+  result = 0;
+  for (i = 0; i < tcp_table->dwNumEntries; i++)
     {
-      _dbus_pipe_invalidate (pipe);
-      return 0;
+      _MIB_TCPROW_EX *p = &tcp_table->table[i];
+      int local_port = ntohs (p->dwLocalPort);
+      int local_address = ntohl (p->dwLocalAddr);
+      if (local_address == INADDR_LOOPBACK && local_port == peer_port)
+        {
+          result = p->dwOwningPid;
+          break;
+        }
     }
-}
 
-#undef FDATA
+  HeapFree (GetProcessHeap(), 0, tcp_table);
+  _dbus_verbose ("got pid %d\n", (int)result);
+  return result;
+}
 
 /**
- * Socket interface
- *
+ * @brief return peer process id from tcp handle for localhost connections
+ * @param handle tcp socket descriptor
+ * @return process id or 0 in case the process id could not be fetched
  */
-
-#ifdef ENABLE_DBUSSOCKET
-static DBusSocket *win_fds = NULL;
-static int win_n_fds = 0; // is this the size? rename to win_fds_size? #
-
-
-#if 0
-#define TO_HANDLE(n)   ((n)^win32_encap_randomizer)
-#define FROM_HANDLE(n) ((n)^win32_encap_randomizer)
-#else
-#define TO_HANDLE(n)   ((n)+0x10000000)
-#define FROM_HANDLE(n) ((n)-0x10000000)
-#define IS_HANDLE(n)   ((n)&0x10000000)
-#endif
-
-
-static
-void
-_dbus_win_deallocate_fd (int fd)
+static dbus_pid_t
+_dbus_get_peer_pid_from_tcp_handle (int handle)
 {
-  _DBUS_LOCK (win_fds);
-  win_fds[FROM_HANDLE (fd)].is_used = 0;
-  _DBUS_UNLOCK (win_fds);
-}
+  struct sockaddr_storage addr;
+  socklen_t len = sizeof (addr);
+  int peer_port;
 
-static
-int
-_dbus_win_allocate_fd (void)
-{
-  int i;
+  dbus_pid_t result;
+  dbus_bool_t is_localhost = FALSE;
 
-  _DBUS_LOCK (win_fds);
+  getpeername (handle, (struct sockaddr *) &addr, &len);
 
-  if (win_fds == NULL)
+  if (addr.ss_family == AF_INET)
     {
-#ifdef _DBUS_WIN_USE_RANDOMIZER
-      DBusString random;
-#endif
-
-      win_n_fds = 16;
-      /* Use malloc to avoid memory leak failure in dbus-test */
-      win_fds = malloc (win_n_fds * sizeof (*win_fds));
-
-      _dbus_assert (win_fds != NULL);
-
-      for (i = 0; i < win_n_fds; i++)
-        win_fds[i].is_used = 0;
-
-#ifdef _DBUS_WIN_USE_RANDOMIZER
-
-      _dbus_string_init (&random);
-      _dbus_generate_random_bytes (&random, sizeof (int));
-      memmove (&win_encap_randomizer, _dbus_string_get_const_data (&random), sizeof (int));
-      win_encap_randomizer &= 0xFF;
-      _dbus_string_free (&random);
-#endif
-
+      struct sockaddr_in *s = (struct sockaddr_in *) &addr;
+      peer_port = ntohs (s->sin_port);
+      is_localhost = (ntohl (s->sin_addr.s_addr) == INADDR_LOOPBACK);
     }
-
-  for (i = 0; i < win_n_fds && win_fds[i].is_used != 0; i++)
-    ;
-
-  if (i == win_n_fds)
+  else if (addr.ss_family == AF_INET6)
     {
-      int oldn = win_n_fds;
-      int j;
-
-      win_n_fds += 16;
-      win_fds = realloc (win_fds, win_n_fds * sizeof (*win_fds));
-
-      _dbus_assert (win_fds != NULL);
-
-      for (j = oldn; j < win_n_fds; j++)
-        win_fds[i].is_used = 0;
+      _dbus_verbose ("FIXME [61922]: IPV6 support not working on windows\n");
+      return 0;
+      /*
+         struct sockaddr_in6 *s = (struct sockaddr_in6 * )&addr;
+         peer_port = ntohs (s->sin6_port);
+         is_localhost = (memcmp(s->sin6_addr.s6_addr, in6addr_loopback.s6_addr, 16) == 0);
+         _dbus_verbose ("IPV6 %08x %08x\n", s->sin6_addr.s6_addr, in6addr_loopback.s6_addr);
+       */
+    }
+  else
+    {
+      _dbus_verbose ("no idea what address family %d is\n", addr.ss_family);
+      return 0;
     }
 
-  memset(&win_fds[i], 0, sizeof(win_fds[i]));
-
-  win_fds[i].is_used = 1;
-  win_fds[i].fd = -1;
-  win_fds[i].port_file_fd = -1;
-  win_fds[i].close_on_exec = FALSE;
-  win_fds[i].non_blocking = FALSE;
-
-  _DBUS_UNLOCK (win_fds);
-
-  return i;
-}
-
-static
-int
-_dbus_create_handle_from_socket (int s)
-{
-  int i;
-  int handle = -1;
-
-  // check: parameter must be a valid value
-  _dbus_assert(s != -1);
-  _dbus_assert(!IS_HANDLE(s));
-
-  // get index of a new position in the map
-  i = _dbus_win_allocate_fd ();
-
-  // fill new posiiton in the map: value->index
-  win_fds[i].fd = s;
-  win_fds[i].is_used = 1;
+  if (!is_localhost)
+    {
+      _dbus_verbose ("could not fetch process id from remote process\n");
+      return 0;
+    }
 
-  // create handle from the index: index->handle
-  handle = TO_HANDLE (i);
+  if (peer_port == 0)
+    {
+      _dbus_verbose
+        ("Error not been able to fetch tcp peer port from connection\n");
+      return 0;
+    }
 
-  _dbus_verbose ("_dbus_create_handle_from_value, value: %d, handle: %d\n", s, handle);
+  _dbus_verbose ("trying to get peers pid");
 
-  return handle;
+  result = get_pid_from_extended_tcp_table (peer_port);
+  if (result > 0)
+      return result;
+  result = get_pid_from_tcp_ex_table (peer_port);
+  return result;
 }
 
-int
-_dbus_socket_to_handle (DBusSocket *s)
+/* Convert GetLastError() to a dbus error.  */
+const char*
+_dbus_win_error_from_last_error (void)
 {
-  int i;
-  int handle = -1;
-
-  // check: parameter must be a valid socket
-  _dbus_assert(s != NULL);
-  _dbus_assert(s->fd != -1);
-  _dbus_assert(!IS_HANDLE(s->fd));
-
-  _DBUS_LOCK (win_fds);
-
-  // at the first call there is no win_fds
-  // will be constructed  _dbus_create_handle_from_socket
-  // because handle = -1
-  if (win_fds != NULL)
+  switch (GetLastError())
     {
-      // search for the value in the map
-      // find the index of the value: value->index
-      for (i = 0; i < win_n_fds; i++)
-        if (win_fds[i].is_used == 1 && win_fds[i].fd == s->fd)
-          {
-            // create handle from the index: index->handle
-            handle = TO_HANDLE (i);
-            break;
-          }
-    }
-  _DBUS_UNLOCK (win_fds);
+    case 0:
+      return DBUS_ERROR_FAILED;
+    
+    case ERROR_NO_MORE_FILES:
+    case ERROR_TOO_MANY_OPEN_FILES:
+      return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
 
+    case ERROR_ACCESS_DENIED:
+    case ERROR_CANNOT_MAKE:
+      return DBUS_ERROR_ACCESS_DENIED;
 
-  if (handle == -1)
-    {
-      handle = _dbus_create_handle_from_socket(s->fd);
-    }
+    case ERROR_NOT_ENOUGH_MEMORY:
+      return DBUS_ERROR_NO_MEMORY;
 
-  _dbus_assert(handle != -1);
+    case ERROR_FILE_EXISTS:
+      return DBUS_ERROR_FILE_EXISTS;
 
-  return handle;
+    case ERROR_FILE_NOT_FOUND:
+    case ERROR_PATH_NOT_FOUND:
+      return DBUS_ERROR_FILE_NOT_FOUND;
+    }
+  
+  return DBUS_ERROR_FAILED;
 }
 
-static
-void 
-_dbus_handle_to_socket_unlocked (int          handle,
-                                 DBusSocket **ptr)
-{
-  int i;
-
-  // check: parameter must be a valid handle
-  _dbus_assert(handle != -1);
-  _dbus_assert(IS_HANDLE(handle));
-  _dbus_assert(ptr != NULL);
 
-  // map from handle to index: handle->index
-  i = FROM_HANDLE (handle);
-
-  _dbus_assert (win_fds != NULL);
-  _dbus_assert (i >= 0 && i < win_n_fds);
+char*
+_dbus_win_error_string (int error_number)
+{
+  char *msg;
 
-  // check for if fd is valid
-  _dbus_assert (win_fds[i].is_used == 1);
+  FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
+                  FORMAT_MESSAGE_IGNORE_INSERTS |
+                  FORMAT_MESSAGE_FROM_SYSTEM,
+                  NULL, error_number, 0,
+                  (LPSTR) &msg, 0, NULL);
 
-  // get socket from index: index->socket
-  *ptr = &win_fds[i];
+  if (msg[strlen (msg) - 1] == '\n')
+    msg[strlen (msg) - 1] = '\0';
+  if (msg[strlen (msg) - 1] == '\r')
+    msg[strlen (msg) - 1] = '\0';
 
-  _dbus_verbose ("_dbus_socket_to_handle_unlocked: socket=%d, handle=%d, index=%d\n", (*ptr)->fd, handle, i);
+  return msg;
 }
 
-void 
-_dbus_handle_to_socket (int          handle,
-                        DBusSocket **ptr)
+void
+_dbus_win_free_error_string (char *string)
 {
-  _dbus_lock_sockets();
-  _dbus_handle_to_socket_unlocked (handle, ptr);
-  _dbus_unlock_sockets();
+  LocalFree (string);
 }
 
-
-#undef TO_HANDLE
-#undef IS_HANDLE
-#undef FROM_HANDLE
-#define FROM_HANDLE(n) 1==DBUS_WIN_DONT_USE__FROM_HANDLE__DIRECTLY
-#define win_fds 1==DBUS_WIN_DONT_USE_win_fds_DIRECTLY
-
-
-#endif
+/**
+ * Socket interface
+ *
+ */
 
 /**
  * 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.
+ * _dbus_read_socket() handles EINTR for you. 
+ * _dbus_read_socket() can return ENOMEM, even though 
+ * regular UNIX read doesn't.
  *
  * @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_socket (int               handle,
+_dbus_read_socket (int               fd,
                    DBusString       *buffer,
                    int               count)
 {
-#ifdef ENABLE_DBUSSOCKET
-  DBusSocket *s;
-#endif
   int bytes_read;
   int start;
   char *data;
@@ -587,44 +394,36 @@ _dbus_read_socket (int               handle,
 
   if (!_dbus_string_lengthen (buffer, count))
     {
-      errno = ENOMEM;
+      _dbus_win_set_errno (ENOMEM);
       return -1;
     }
 
   data = _dbus_string_get_data_len (buffer, start, count);
 
-#ifdef ENABLE_DBUSSOCKET
-  _dbus_handle_to_socket(handle, &s);
+ again:
+  _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
+  bytes_read = recv (fd, data, count, 0);
+  
+  if (bytes_read == SOCKET_ERROR)
+       {
+         DBUS_SOCKET_SET_ERRNO();
+         _dbus_verbose ("recv: failed: %s (%d)\n", _dbus_strerror (errno), errno);
+         bytes_read = -1;
+       }
+       else
+         _dbus_verbose ("recv: = %d\n", bytes_read);
 
-  if(s->is_used)
-    {
-      _dbus_verbose ("recv: count=%d socket=%d\n", count, s->fd);
-      bytes_read = recv (s->fd, data, count, 0);
-#else
-       if(1)
+  if (bytes_read < 0)
     {
-      _dbus_verbose ("recv: count=%d socket=%d\n", count, handle);
-      bytes_read = recv (handle, data, count, 0);
-#endif
-      if (bytes_read == SOCKET_ERROR)
+      if (errno == EINTR)
+        goto again;
+      else     
         {
-          DBUS_SOCKET_SET_ERRNO();
-          _dbus_verbose ("recv: failed: %s\n", _dbus_strerror (errno));
-          bytes_read = -1;
+          /* put length back (note that this doesn't actually realloc anything) */
+          _dbus_string_set_length (buffer, start);
+          return -1;
         }
-      else
-        _dbus_verbose ("recv: = %d\n", bytes_read);
-    }
-  else
-    {
-      _dbus_assert_not_reached ("no valid socket");
-    }
-
-  if (bytes_read < 0)
-    {
-      /* put length back (note that this doesn't actually realloc anything) */
-      _dbus_string_set_length (buffer, start);
-      return -1;
     }
   else
     {
@@ -632,7 +431,6 @@ _dbus_read_socket (int               handle,
       _dbus_string_set_length (buffer, start + bytes_read);
 
 #if 0
-
       if (bytes_read > 0)
         _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
 #endif
@@ -652,47 +450,33 @@ _dbus_read_socket (int               handle,
  * @returns the number of bytes written or -1 on error
  */
 int
-_dbus_write_socket (int               handle,
+_dbus_write_socket (int               fd,
                     const DBusString *buffer,
                     int               start,
                     int               len)
 {
-#ifdef ENABLE_DBUSSOCKET
-  DBusSocket *s;
-#endif
-  int is_used;
   const char *data;
   int bytes_written;
 
   data = _dbus_string_get_const_data_len (buffer, start, len);
 
-#ifdef ENABLE_DBUSSOCKET
-  _dbus_handle_to_socket(handle, &s);
+ again:
 
-  if (s->is_used)
-    {
-      _dbus_verbose ("send: len=%d socket=%d\n", len, s->fd);
-      bytes_written = send (s->fd, data, len, 0);
-#else
-  if (1)
-    {
-      _dbus_verbose ("send: len=%d socket=%d\n", len, handle);
-         bytes_written = send (handle, data, len, 0);
-#endif
-      if (bytes_written == SOCKET_ERROR)
-        {
-          DBUS_SOCKET_SET_ERRNO();
-          _dbus_verbose ("send: failed: %s\n", _dbus_strerror (errno));
-          bytes_written = -1;
-        }
-      else
-        _dbus_verbose ("send: = %d\n", bytes_written);
-    }
-  else
+  _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
+  bytes_written = send (fd, data, len, 0);
+
+  if (bytes_written == SOCKET_ERROR)
     {
-      _dbus_assert_not_reached ("unhandled fd type");
+      DBUS_SOCKET_SET_ERRNO();
+      _dbus_verbose ("send: failed: %s\n", _dbus_strerror_from_errno ());
+      bytes_written = -1;
     }
+    else
+      _dbus_verbose ("send: = %d\n", bytes_written);
 
+  if (bytes_written < 0 && errno == EINTR)
+    goto again;
+    
 #if 0
   if (bytes_written > 0)
     _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
@@ -710,79 +494,27 @@ _dbus_write_socket (int               handle,
  * @returns #FALSE if error set
  */
 dbus_bool_t
-_dbus_close_socket (int        handle,
+_dbus_close_socket (int        fd,
                     DBusError *error)
 {
-#ifdef ENABLE_DBUSSOCKET
-  DBusSocket *s;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-
-  _dbus_lock_sockets();
-
-  _dbus_handle_to_socket_unlocked (handle, &s);
-
-
-  if (s->is_used)
-    {
-      if (s->port_file_fd >= 0)
-        {
-          _chsize (s->port_file_fd, 0);
-          close (s->port_file_fd);
-          s->port_file_fd = -1;
-          unlink (_dbus_string_get_const_data (&s->port_file));
-          free ((char *) _dbus_string_get_const_data (&s->port_file));
-        }
-
-      if (closesocket (s->fd) == SOCKET_ERROR)
-        {
-          DBUS_SOCKET_SET_ERRNO ();
-          dbus_set_error (error, _dbus_error_from_errno (errno),
-              "Could not close socket: socket=%d, handle=%d, %s",
-                          s->fd, handle, _dbus_strerror (errno));
-          _dbus_unlock_sockets();
-          return FALSE;
-        }
-      _dbus_verbose ("_dbus_close_socket: socket=%d, handle=%d\n",
-                     s->fd, handle);
-    }
-  else
-    {
-      _dbus_assert_not_reached ("unhandled fd type");
-    }
-
-  _dbus_unlock_sockets();
-
-  _dbus_win_deallocate_fd (handle);
-
-  return TRUE;
-
-#else
-
   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
 
-
-  if (1)
-    {
-      if (closesocket (handle) == SOCKET_ERROR)
-        {
-          DBUS_SOCKET_SET_ERRNO ();
-          dbus_set_error (error, _dbus_error_from_errno (errno),
-              "Could not close socket: socket=%d, , %s",
-                          handle, _dbus_strerror (errno));
-          return FALSE;
-        }
-      _dbus_verbose ("_dbus_close_socket: socket=%d, \n",
-                     handle);
-    }
-  else
+ again:
+  if (closesocket (fd) == SOCKET_ERROR)
     {
-      _dbus_assert_not_reached ("unhandled fd type");
+      DBUS_SOCKET_SET_ERRNO ();
+      
+      if (errno == EINTR)
+        goto again;
+        
+      dbus_set_error (error, _dbus_error_from_errno (errno),
+                      "Could not close socket: socket=%d, , %s",
+                      fd, _dbus_strerror_from_errno ());
+      return FALSE;
     }
+  _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
 
   return TRUE;
-#endif
-
 }
 
 /**
@@ -790,42 +522,23 @@ _dbus_close_socket (int        handle,
  * on exec. Should be called for all file
  * descriptors in D-Bus code.
  *
- * @param fd the file descriptor
+ * @param handle the Windows HANDLE
  */
 void
-_dbus_fd_set_close_on_exec (int handle)
+_dbus_fd_set_close_on_exec (intptr_t handle)
 {
-#ifdef ENABLE_DBUSSOCKET
-  DBusSocket *s;
-  if (handle < 0)
-    return;
-
-  _dbus_lock_sockets();
-
-  _dbus_handle_to_socket_unlocked (handle, &s);
-  s->close_on_exec = TRUE;
-
-  _dbus_unlock_sockets();
-#else
-  /* TODO unic code.
-  int val;
-  
-  val = fcntl (fd, F_GETFD, 0);
-  
-  if (val < 0)
-    return;
-
-  val |= FD_CLOEXEC;
-  
-  fcntl (fd, F_SETFD, val);
-  */
-#endif
+  if ( !SetHandleInformation( (HANDLE) handle,
+                        HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE,
+                        0 /*disable both flags*/ ) )
+    {
+      _dbus_win_warn_win_error ("Disabling socket handle inheritance failed:", GetLastError());
+    }
 }
 
 /**
  * Sets a file descriptor to be nonblocking.
  *
- * @param fd the file descriptor.
+ * @param handle the file descriptor.
  * @param error address of error location.
  * @returns #TRUE on success.
  */
@@ -833,56 +546,20 @@ dbus_bool_t
 _dbus_set_fd_nonblocking (int             handle,
                           DBusError      *error)
 {
-#ifdef ENABLE_DBUSSOCKET
-  DBusSocket *s;
   u_long one = 1;
 
   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
 
-  _dbus_lock_sockets();
-
-  _dbus_handle_to_socket_unlocked(handle, &s);
-
-  if (s->is_used)
-    {
-      if (ioctlsocket (s->fd, FIONBIO, &one) == SOCKET_ERROR)
-        {
-          dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
-                          "Failed to set socket %d:%d to nonblocking: %s", s->fd,
-                          _dbus_strerror (WSAGetLastError ()));
-          _dbus_unlock_sockets();
-          return FALSE;
-        }
-    }
-  else
+  if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
     {
-      _dbus_assert_not_reached ("unhandled fd type");
+      DBUS_SOCKET_SET_ERRNO ();
+      dbus_set_error (error, _dbus_error_from_errno (errno),
+                      "Failed to set socket %d:%d to nonblocking: %s", handle,
+                      _dbus_strerror_from_errno ());
+      return FALSE;
     }
 
-  _dbus_unlock_sockets();
-
   return TRUE;
-#else
-  u_long one = 1;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-
-  if (1)
-    {
-      if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
-        {
-          dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
-                          "Failed to set socket %d:%d to nonblocking: %s", handle,
-                          _dbus_strerror (WSAGetLastError ()));
-          return FALSE;
-        }
-    }
-  else
-    {
-      _dbus_assert_not_reached ("unhandled fd type");
-    }
-  return TRUE;
-#endif
 }
 
 
@@ -907,7 +584,7 @@ _dbus_set_fd_nonblocking (int             handle,
  * @returns total bytes written from both buffers, or -1 on error
  */
 int
-_dbus_write_socket_two (int               handle,
+_dbus_write_socket_two (int               fd,
                         const DBusString *buffer1,
                         int               start1,
                         int               len1,
@@ -915,14 +592,11 @@ _dbus_write_socket_two (int               handle,
                         int               start2,
                         int               len2)
 {
-#ifdef ENABLE_DBUSSOCKET
-  DBusSocket *s;
   WSABUF vectors[2];
   const char *data1;
   const char *data2;
   int rc;
   DWORD bytes_written;
-  int ret1;
 
   _dbus_assert (buffer1 != NULL);
   _dbus_assert (start1 >= 0);
@@ -930,7 +604,6 @@ _dbus_write_socket_two (int               handle,
   _dbus_assert (len1 >= 0);
   _dbus_assert (len2 >= 0);
 
-  _dbus_handle_to_socket(handle, &s);
 
   data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
 
@@ -943,83 +616,41 @@ _dbus_write_socket_two (int               handle,
       len2 = 0;
     }
 
-  if (s->is_used)
-    {
-      vectors[0].buf = (char*) data1;
-      vectors[0].len = len1;
-      vectors[1].buf = (char*) data2;
-      vectors[1].len = len2;
-
-      _dbus_verbose ("WSASend: len1+2=%d+%d socket=%d\n", len1, len2, s->fd);
-      rc = WSASend (s->fd, vectors, data2 ? 2 : 1, &bytes_written,
-                    0, NULL, NULL);
-      if (rc < 0)
-        {
-          DBUS_SOCKET_SET_ERRNO ();
-          _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
-          bytes_written = -1;
-        }
-      else
-        _dbus_verbose ("WSASend: = %ld\n", bytes_written);
-      return bytes_written;
-    }
-  else
-    {
-      _dbus_assert_not_reached ("unhandled fd type");
-    }
-  return 0;
-#else
-  WSABUF vectors[2];
-  const char *data1;
-  const char *data2;
-  int rc;
-  DWORD bytes_written;
-  int ret1;
-
-  _dbus_assert (buffer1 != NULL);
-  _dbus_assert (start1 >= 0);
-  _dbus_assert (start2 >= 0);
-  _dbus_assert (len1 >= 0);
-  _dbus_assert (len2 >= 0);
-
-
-  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].buf = (char*) data1;
+  vectors[0].len = len1;
+  vectors[1].buf = (char*) data2;
+  vectors[1].len = len2;
 
-  if (1)
+ again:
+  _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
+  rc = WSASend (fd, 
+                vectors,
+                data2 ? 2 : 1, 
+                &bytes_written,
+                0, 
+                NULL, 
+                NULL);
+                
+  if (rc == SOCKET_ERROR)
     {
-      vectors[0].buf = (char*) data1;
-      vectors[0].len = len1;
-      vectors[1].buf = (char*) data2;
-      vectors[1].len = len2;
-
-      _dbus_verbose ("WSASend: len1+2=%d+%d socket=%d\n", len1, len2, handle);
-      rc = WSASend (handle, vectors, data2 ? 2 : 1, &bytes_written,
-                    0, NULL, NULL);
-      if (rc < 0)
-        {
-          DBUS_SOCKET_SET_ERRNO ();
-          _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
-          bytes_written = -1;
-        }
-      else
-        _dbus_verbose ("WSASend: = %ld\n", bytes_written);
-      return bytes_written;
+      DBUS_SOCKET_SET_ERRNO ();
+      _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror_from_errno ());
+      bytes_written = -1;
     }
   else
-    {
-      _dbus_assert_not_reached ("unhandled fd type");
-    }
-  return 0;
-#endif
+    _dbus_verbose ("WSASend: = %ld\n", bytes_written);
+    
+  if (bytes_written < 0 && errno == EINTR)
+    goto again;
+      
+  return bytes_written;
+}
+
+dbus_bool_t
+_dbus_socket_is_invalid (int fd)
+{
+    return fd == INVALID_SOCKET ? TRUE : FALSE;
 }
 
 #if 0
@@ -1042,527 +673,93 @@ _dbus_connect_named_pipe (const char     *path,
 #endif
 
 
-#ifdef ENABLE_DBUSUSERINFO
-dbus_bool_t
-_dbus_account_to_win_sid (const wchar_t  *waccount,
-                          void          **ppsid,
-                          DBusError      *error)
+
+void
+_dbus_win_startup_winsock (void)
 {
-  dbus_bool_t retval = FALSE;
-  DWORD sid_length, wdomain_length;
-  SID_NAME_USE use;
-  wchar_t *wdomain;
+  /* Straight from MSDN, deuglified */
 
-  *ppsid = NULL;
+  static dbus_bool_t beenhere = FALSE;
 
-  sid_length = 0;
-  wdomain_length = 0;
-  if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
-                           NULL, &wdomain_length, &use)
-      && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
-    {
-      _dbus_win_set_error_from_win_error (error, GetLastError ());
-      return FALSE;
-    }
+  WORD wVersionRequested;
+  WSADATA wsaData;
+  int err;
 
-  *ppsid = dbus_malloc (sid_length);
-  if (!*ppsid)
-    {
-      _DBUS_SET_OOM (error);
-      return FALSE;
-    }
+  if (beenhere)
+    return;
 
-  wdomain = dbus_new (wchar_t, wdomain_length);
-  if (!wdomain)
-    {
-      _DBUS_SET_OOM (error);
-      goto out1;
-    }
+  wVersionRequested = MAKEWORD (2, 0);
 
-  if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
-                           wdomain, &wdomain_length, &use))
+  err = WSAStartup (wVersionRequested, &wsaData);
+  if (err != 0)
     {
-      _dbus_win_set_error_from_win_error (error, GetLastError ());
-      goto out2;
+      _dbus_assert_not_reached ("Could not initialize WinSock");
+      _dbus_abort ();
     }
 
-  if (!IsValidSid ((PSID) *ppsid))
+  /* Confirm that the WinSock DLL supports 2.0.  Note that if the DLL
+   * supports versions greater than 2.0 in addition to 2.0, it will
+   * still return 2.0 in wVersion since that is the version we
+   * requested.
+   */
+  if (LOBYTE (wsaData.wVersion) != 2 ||
+      HIBYTE (wsaData.wVersion) != 0)
     {
-      dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
-      goto out2;
+      _dbus_assert_not_reached ("No usable WinSock found");
+      _dbus_abort ();
     }
 
-  retval = TRUE;
+  beenhere = TRUE;
+}
 
-out2:
-  dbus_free (wdomain);
-out1:
-  if (!retval)
-    {
-      dbus_free (*ppsid);
-      *ppsid = NULL;
-    }
 
-  return retval;
-}
 
-dbus_bool_t
-fill_win_user_info_name_and_groups (wchar_t      *wname,
-                                    wchar_t      *wdomain,
-                                    DBusUserInfo *info,
-                                    DBusError    *error)
-{
-#ifdef DBUS_WINCE
-       return TRUE;
-#else
-  dbus_bool_t retval = FALSE;
-  char *name, *domain;
-  LPLOCALGROUP_USERS_INFO_0 local_groups = NULL;
-  LPGROUP_USERS_INFO_0 global_groups = NULL;
-  DWORD nread, ntotal;
 
-  name = _dbus_win_utf16_to_utf8 (wname, error);
-  if (!name)
-    return FALSE;
 
-  domain = _dbus_win_utf16_to_utf8 (wdomain, error);
-  if (!domain)
-    goto out0;
 
-  info->username = dbus_malloc (strlen (domain) + 1 + strlen (name) + 1);
-  if (!info->username)
-    {
-      _DBUS_SET_OOM (error);
-      goto out1;
-    }
 
-  strcpy (info->username, domain);
-  strcat (info->username, "\\");
-  strcat (info->username, name);
 
-  info->n_group_ids = 0;
-  if (NetUserGetLocalGroups (NULL, wname, 0, LG_INCLUDE_INDIRECT,
-                             (LPBYTE *) &local_groups, MAX_PREFERRED_LENGTH,
-                             &nread, &ntotal) == NERR_Success)
-    {
-      DWORD i;
-      int n;
 
-      info->group_ids = dbus_new (dbus_gid_t, nread);
-      if (!info->group_ids)
-        {
-          _DBUS_SET_OOM (error);
-          goto out3;
-        }
+/************************************************************************
+ UTF / string code
+ ************************************************************************/
 
-      for (i = n = 0; i < nread; i++)
-        {
-          PSID group_sid;
-          if (_dbus_account_to_win_sid (local_groups[i].lgrui0_name,
-                                        &group_sid, error))
-            {
-              info->group_ids[n++] = _dbus_win_sid_to_uid_t (group_sid);
-              dbus_free (group_sid);
-            }
-        }
-      info->n_group_ids = n;
-    }
+/**
+ * Measure the message length without terminating nul 
+ */
+int _dbus_printf_string_upper_bound (const char *format,
+                                     va_list args)
+{
+  /* MSVCRT's vsnprintf semantics are a bit different */
+  char buf[1024];
+  int bufsize;
+  int len;
+  va_list args_copy;
 
-  if (NetUserGetGroups (NULL, wname, 0,
-                        (LPBYTE *) &global_groups, MAX_PREFERRED_LENGTH,
-                        &nread, &ntotal) == NERR_Success)
+  bufsize = sizeof (buf);
+  DBUS_VA_COPY (args_copy, args);
+  len = _vsnprintf (buf, bufsize - 1, format, args_copy);
+  va_end (args_copy);
+
+  while (len == -1) /* try again */
     {
-      DWORD i;
-      int n = info->n_group_ids;
+      char *p;
 
-      info->group_ids = dbus_realloc (info->group_ids, (n + nread) * sizeof (dbus_gid_t));
-      if (!info->group_ids)
-        {
-          _DBUS_SET_OOM (error);
-          goto out4;
-        }
+      bufsize *= 2;
 
-      for (i = 0; i < nread; i++)
-        {
-          PSID group_sid;
-          if (_dbus_account_to_win_sid (global_groups[i].grui0_name,
-                                        &group_sid, error))
-            {
-              info->group_ids[n++] = _dbus_win_sid_to_uid_t (group_sid);
-              dbus_free (group_sid);
-            }
-        }
-      info->n_group_ids = n;
+      p = malloc (bufsize);
+
+      if (p == NULL)
+        return -1;
+
+      DBUS_VA_COPY (args_copy, args);
+      len = _vsnprintf (p, bufsize - 1, format, args_copy);
+      va_end (args_copy);
+      free (p);
     }
 
-  if (info->n_group_ids > 0)
-    {
-      /* FIXME: find out actual primary group */
-      info->primary_gid = info->group_ids[0];
-    }
-  else
-    {
-      info->group_ids = dbus_new (dbus_gid_t, 1);
-      info->n_group_ids = 1;
-      info->group_ids[0] = DBUS_GID_UNSET;
-      info->primary_gid = DBUS_GID_UNSET;
-    }
-
-  retval = TRUE;
-
-out4:
-  if (global_groups != NULL)
-    NetApiBufferFree (global_groups);
-out3:
-  if (local_groups != NULL)
-    NetApiBufferFree (local_groups);
-out1:
-  dbus_free (domain);
-out0:
-  dbus_free (name);
-
-  return retval;
-#endif //DBUS_WINCE
-}
-
-dbus_bool_t
-fill_win_user_info_homedir (wchar_t     *wname,
-                            wchar_t     *wdomain,
-                            DBusUserInfo *info,
-                            DBusError    *error)
-{
-#ifdef DBUS_WINCE
-       //TODO
-       return TRUE;
-#else
-  dbus_bool_t retval = FALSE;
-  USER_INFO_1 *user_info = NULL;
-  wchar_t wcomputername[MAX_COMPUTERNAME_LENGTH + 1];
-  DWORD wcomputername_length = MAX_COMPUTERNAME_LENGTH + 1;
-  dbus_bool_t local_computer;
-  wchar_t *dc = NULL;
-  NET_API_STATUS ret = 0;
-
-  /* If the domain is this computer's name, assume it's a local user.
-   * Otherwise look up a DC for the domain, and ask it.
-   */
-
-  GetComputerNameW (wcomputername, &wcomputername_length);
-  local_computer = (wcsicmp (wcomputername, wdomain) == 0);
-
-  if (!local_computer)
-    {
-      ret = NetGetAnyDCName (NULL, wdomain, (LPBYTE *) &dc);
-      if (ret != NERR_Success)
-        {
-          info->homedir = _dbus_strdup ("\\");
-          _dbus_verbose("NetGetAnyDCName() failed with errorcode %d '%s'\n",ret,_dbus_lm_strerror(ret));
-          return TRUE;
-        }
-    }
-
-  /* No way to find out the profile of another user, let's try the
-   * "home directory" from NetUserGetInfo's USER_INFO_1.
-   */
-  ret = NetUserGetInfo (dc, wname, 1, (LPBYTE *) &user_info);
-  if (ret == NERR_Success )
-    if(user_info->usri1_home_dir != NULL &&
-        user_info->usri1_home_dir != (LPWSTR)0xfeeefeee &&  /* freed memory http://www.gamedev.net/community/forums/topic.asp?topic_id=158402 */
-        user_info->usri1_home_dir[0] != '\0')
-      {
-        info->homedir = _dbus_win_utf16_to_utf8 (user_info->usri1_home_dir, error);
-        if (!info->homedir)
-          goto out1;
-      }
-    else
-      {
-        _dbus_verbose("NetUserGetInfo() returned no home dir entry\n");
-        /* Not set, so use something random. */
-        info->homedir = _dbus_strdup ("\\");
-      }
-  else
-    {
-      char *dc_string = _dbus_win_utf16_to_utf8(dc,error);
-         char *user_name = _dbus_win_utf16_to_utf8(wname,error);
-      _dbus_verbose("NetUserGetInfo() for user '%s' failed with errorcode %d '%s', %s\n",user_name, ret,_dbus_lm_strerror(ret),dc_string);
-      dbus_free(user_name);
-      dbus_free(dc_string);
-      /* Not set, so use something random. */
-      info->homedir = _dbus_strdup ("\\");
-    }
-
-  retval = TRUE;
-
-out1:
-  if (dc != NULL)
-    NetApiBufferFree (dc);
-  if (user_info != NULL)
-    NetApiBufferFree (user_info);
-
-  return retval;
-#endif //DBUS_WINCE
-}
-
-dbus_bool_t
-fill_win_user_info_from_name (wchar_t      *wname,
-                              DBusUserInfo *info,
-                              DBusError    *error)
-{
-#ifdef DBUS_WINCE
-       return TRUE;
-       //TODO
-#else
-  dbus_bool_t retval = FALSE;
-  PSID sid;
-  wchar_t *wdomain;
-  DWORD sid_length, wdomain_length;
-  SID_NAME_USE use;
-
-  sid_length = 0;
-  wdomain_length = 0;
-  if (!LookupAccountNameW (NULL, wname, NULL, &sid_length,
-                           NULL, &wdomain_length, &use) &&
-      GetLastError () != ERROR_INSUFFICIENT_BUFFER)
-    {
-      _dbus_win_set_error_from_win_error (error, GetLastError ());
-      return FALSE;
-    }
-
-  sid = dbus_malloc (sid_length);
-  if (!sid)
-    {
-      _DBUS_SET_OOM (error);
-      return FALSE;
-    }
-
-  wdomain = dbus_new (wchar_t, wdomain_length);
-  if (!wdomain)
-    {
-      _DBUS_SET_OOM (error);
-      goto out0;
-    }
-
-  if (!LookupAccountNameW (NULL, wname, sid, &sid_length,
-                           wdomain, &wdomain_length, &use))
-    {
-      _dbus_win_set_error_from_win_error (error, GetLastError ());
-      goto out1;
-    }
-
-  if (!IsValidSid (sid))
-    {
-      dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
-      goto out1;
-    }
-
-  info->uid = _dbus_win_sid_to_uid_t (sid);
-
-  if (!fill_win_user_info_name_and_groups (wname, wdomain, info, error))
-    goto out1;
-
-  if (!fill_win_user_info_homedir (wname, wdomain, info, error))
-    goto out1;
-
-  retval = TRUE;
-
-out1:
-  dbus_free (wdomain);
-out0:
-  dbus_free (sid);
-
-  return retval;
-#endif //DBUS_WINCE
-}
-
-dbus_bool_t
-_dbus_win_sid_to_name_and_domain (dbus_uid_t uid,
-                                  wchar_t  **wname,
-                                  wchar_t  **wdomain,
-                                  DBusError *error)
-{
-#ifdef DBUS_WINCE
-       return TRUE;
-       //TODO
-#else
-  PSID sid;
-  DWORD wname_length, wdomain_length;
-  SID_NAME_USE use;
-
-  if (!_dbus_uid_t_to_win_sid (uid, &sid))
-    {
-      _dbus_win_set_error_from_win_error (error, GetLastError ());
-      return FALSE;
-    }
-
-  wname_length = 0;
-  wdomain_length = 0;
-  if (!LookupAccountSidW (NULL, sid, NULL, &wname_length,
-                          NULL, &wdomain_length, &use) &&
-      GetLastError () != ERROR_INSUFFICIENT_BUFFER)
-    {
-      _dbus_win_set_error_from_win_error (error, GetLastError ());
-      goto out0;
-    }
-
-  *wname = dbus_new (wchar_t, wname_length);
-  if (!*wname)
-    {
-      _DBUS_SET_OOM (error);
-      goto out0;
-    }
-
-  *wdomain = dbus_new (wchar_t, wdomain_length);
-  if (!*wdomain)
-    {
-      _DBUS_SET_OOM (error);
-      goto out1;
-    }
-
-  if (!LookupAccountSidW (NULL, sid, *wname, &wname_length,
-                          *wdomain, &wdomain_length, &use))
-    {
-      _dbus_win_set_error_from_win_error (error, GetLastError ());
-      goto out2;
-    }
-
-  return TRUE;
-
-out2:
-  dbus_free (*wdomain);
-  *wdomain = NULL;
-out1:
-  dbus_free (*wname);
-  *wname = NULL;
-out0:
-  LocalFree (sid);
-
-  return FALSE;
-#endif //DBUS_WINCE
-}
-
-dbus_bool_t
-fill_win_user_info_from_uid (dbus_uid_t    uid,
-                             DBusUserInfo *info,
-                             DBusError    *error)
-{
-#ifdef DBUS_WINCE
-       return TRUE;
-       //TODO
-#else
-  PSID sid;
-  dbus_bool_t retval = FALSE;
-  wchar_t *wname, *wdomain;
-
-  info->uid = uid;
-
-  if (!_dbus_win_sid_to_name_and_domain (uid, &wname, &wdomain, error))
-    {
-      _dbus_verbose("%s after _dbus_win_sid_to_name_and_domain\n",__FUNCTION__);
-      return FALSE;
-    }
-
-  if (!fill_win_user_info_name_and_groups (wname, wdomain, info, error))
-    {
-      _dbus_verbose("%s after fill_win_user_info_name_and_groups\n",__FUNCTION__);
-      goto out0;
-    }
-
-
-  if (!fill_win_user_info_homedir (wname, wdomain, info, error))
-    {
-      _dbus_verbose("%s after fill_win_user_info_homedir\n",__FUNCTION__);
-      goto out0;
-    }
-
-  retval = TRUE;
-
-out0:
-  dbus_free (wdomain);
-  dbus_free (wname);
-
-  return retval;
-#endif //DBUS_WINCE
-}
-
-#endif
-
-
-void
-_dbus_win_startup_winsock (void)
-{
-  /* Straight from MSDN, deuglified */
-
-  static dbus_bool_t beenhere = FALSE;
-
-  WORD wVersionRequested;
-  WSADATA wsaData;
-  int err;
-
-  if (beenhere)
-    return;
-
-  wVersionRequested = MAKEWORD (2, 0);
-
-  err = WSAStartup (wVersionRequested, &wsaData);
-  if (err != 0)
-    {
-      _dbus_assert_not_reached ("Could not initialize WinSock");
-      _dbus_abort ();
-    }
-
-  /* Confirm that the WinSock DLL supports 2.0.  Note that if the DLL
-   * supports versions greater than 2.0 in addition to 2.0, it will
-   * still return 2.0 in wVersion since that is the version we
-   * requested.
-   */
-  if (LOBYTE (wsaData.wVersion) != 2 ||
-      HIBYTE (wsaData.wVersion) != 0)
-    {
-      _dbus_assert_not_reached ("No usable WinSock found");
-      _dbus_abort ();
-    }
-
-  beenhere = TRUE;
-}
-
-
-
-
-
-
-
-
-
-/************************************************************************
- UTF / string code
- ************************************************************************/
-
-/**
- * Measure the message length without terminating nul 
- */
-int _dbus_printf_string_upper_bound (const char *format,
-                                     va_list args)
-{
-  /* MSVCRT's vsnprintf semantics are a bit different */
-  /* The C library source in the Platform SDK indicates that this
-   * would work, but alas, it doesn't. At least not on Windows
-   * 2000. Presumably those sources correspond to the C library on
-   * some newer or even future Windows version.
-   *
-    len = _vsnprintf (NULL, _DBUS_INT_MAX, format, args);
-   */
-  char p[1024];
-  int len;
-  len = _vsnprintf (p, sizeof(p)-1, format, args);
-  if (len == -1) // try again
-    {
-      char *p;
-      p = malloc (strlen(format)*3);
-      len = _vsnprintf (p, sizeof(p)-1, format, args);
-      free(p);
-    }
   return len;
 }
 
@@ -1663,7 +860,6 @@ _dbus_win_utf16_to_utf8 (const wchar_t *str,
 
 /************************************************************************
  
- uid ... <-> win sid functions
  
  ************************************************************************/
 
@@ -1730,209 +926,107 @@ out1:
   return retval;
 }
 
-#ifdef ENABLE_UID_TO_SID
-static void
-_sid_atom_cache_shutdown (void *unused)
-{
-  DBusHashIter iter;
-  _DBUS_LOCK (sid_atom_cache);
-  _dbus_hash_iter_init (sid_atom_cache, &iter);
-  while (_dbus_hash_iter_next (&iter))
-    {
-      ATOM atom;
-      atom = (ATOM) _dbus_hash_iter_get_value (&iter);
-      GlobalDeleteAtom(atom);
-      _dbus_hash_iter_remove_entry(&iter);
-    }
-  _DBUS_UNLOCK (sid_atom_cache);
-  _dbus_hash_table_unref (sid_atom_cache);
-  sid_atom_cache = NULL;
-}
+/** @} end of sysdeps-win */
+
 
 /**
- * Returns the 2-way associated dbus_uid_t form a SID.
- *
- * @param psid pointer to the SID
+ * The only reason this is separate from _dbus_getpid() is to allow it
+ * on Windows for logging but not for other purposes.
+ * 
+ * @returns process ID to put in log messages
  */
-dbus_uid_t
-_dbus_win_sid_to_uid_t (PSID psid)
-{
-  dbus_uid_t uid;
-  dbus_uid_t olduid;
-  char *string;
-  ATOM atom;
-
-  if (!IsValidSid (psid))
-    {
-      _dbus_verbose("%s invalid sid\n",__FUNCTION__);
-      return DBUS_UID_UNSET;
-    }
-  if (!ConvertSidToStringSidA (psid, &string))
-    {
-      _dbus_verbose("%s invalid sid\n",__FUNCTION__);
-      return DBUS_UID_UNSET;
-    }
-
-  atom = GlobalAddAtom(string);
-
-  if (atom == 0)
-    {
-      _dbus_verbose("%s GlobalAddAtom failed\n",__FUNCTION__);
-      LocalFree (string);
-      return DBUS_UID_UNSET;
-    }
+unsigned long
+_dbus_pid_for_log (void)
+{
+  return _dbus_getpid ();
+}
 
-  _DBUS_LOCK (sid_atom_cache);
+#ifndef DBUS_WINCE
 
-  if (sid_atom_cache == NULL)
-    {
-      sid_atom_cache = _dbus_hash_table_new (DBUS_HASH_ULONG, NULL, NULL);
-      _dbus_register_shutdown_func (_sid_atom_cache_shutdown, NULL);
-    }
+static BOOL is_winxp_sp3_or_lower()
+{
+   OSVERSIONINFOEX osvi;
+   DWORDLONG dwlConditionMask = 0;
+   int op=VER_LESS_EQUAL;
 
-  uid = atom;
-  olduid = (dbus_uid_t) _dbus_hash_table_lookup_ulong (sid_atom_cache, uid);
+   // Initialize the OSVERSIONINFOEX structure.
 
-  if (olduid)
-    {
-      _dbus_verbose("%s sid with id %i found in cache\n",__FUNCTION__, olduid);
-      uid = olduid;
-    }
-  else
-    {
-      _dbus_hash_table_insert_ulong (sid_atom_cache, uid, (void*) uid);
-      _dbus_verbose("%s sid %s added with uid %i to cache\n",__FUNCTION__, string, uid);
-    }
+   ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
+   osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
+   osvi.dwMajorVersion = 5;
+   osvi.dwMinorVersion = 1;
+   osvi.wServicePackMajor = 3;
+   osvi.wServicePackMinor = 0;
 
-  _DBUS_UNLOCK (sid_atom_cache);
+   // Initialize the condition mask.
 
-  return uid;
-}
+   VER_SET_CONDITION( dwlConditionMask, VER_MAJORVERSION, op );
+   VER_SET_CONDITION( dwlConditionMask, VER_MINORVERSION, op );
+   VER_SET_CONDITION( dwlConditionMask, VER_SERVICEPACKMAJOR, op );
+   VER_SET_CONDITION( dwlConditionMask, VER_SERVICEPACKMINOR, op );
 
-dbus_bool_t  _dbus_uid_t_to_win_sid (dbus_uid_t uid, PSID *ppsid)
-{
-  void* atom;
-  char string[255];
+   // Perform the test.
 
-  atom = _dbus_hash_table_lookup_ulong (sid_atom_cache, uid);
-  if (atom == NULL)
-    {
-      _dbus_verbose("%s uid %i not found in cache\n",__FUNCTION__,uid);
-      return FALSE;
-    }
-  memset( string, '.', sizeof(string) );
-  if (!GlobalGetAtomNameA( (ATOM) atom, string, 255 ))
-    {
-      _dbus_verbose("%s uid %i not found in cache\n",__FUNCTION__, uid);
-      return FALSE;
-    }
-  if (!ConvertStringSidToSidA(string, ppsid))
-    {
-      _dbus_verbose("%s could not convert %s into sid \n",__FUNCTION__, string);
-      return FALSE;
-    }
-  _dbus_verbose("%s converted %s into sid \n",__FUNCTION__, string);
-  return TRUE;
+   return VerifyVersionInfo(
+      &osvi,
+      VER_MAJORVERSION | VER_MINORVERSION |
+      VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR,
+      dwlConditionMask);
 }
-#endif
-
-/** @} end of sysdeps-win */
-
 
-/** Gets our UID
- * @returns process UID
+/** Gets our SID
+ * @param sid points to sid buffer, need to be freed with LocalFree()
+ * @param process_id the process id for which the sid should be returned
+ * @returns process sid
  */
-dbus_uid_t
-_dbus_getuid(void)
+static dbus_bool_t
+_dbus_getsid(char **sid, dbus_pid_t process_id)
 {
-#ifndef ENABLE_UID_TO_SID
-       return DBUS_UID_UNSET;
-#else
-  dbus_uid_t retval = DBUS_UID_UNSET;
-  HANDLE process_token = NULL;
+  HANDLE process_token = INVALID_HANDLE_VALUE;
   TOKEN_USER *token_user = NULL;
   DWORD n;
+  PSID psid;
+  int retval = FALSE;
 
-  if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
-    _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
-  else if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
+  HANDLE process_handle = OpenProcess(is_winxp_sp3_or_lower() ? PROCESS_QUERY_INFORMATION : PROCESS_QUERY_LIMITED_INFORMATION, FALSE, process_id);
+
+  if (!OpenProcessToken (process_handle, TOKEN_QUERY, &process_token))
+    {
+      _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
+      goto failed;
+    }
+  if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
             && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
            || (token_user = alloca (n)) == NULL
            || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
-    _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
-  else
-    retval = _dbus_win_sid_to_uid_t (token_user->User.Sid);
-
-  if (process_token != NULL)
-    CloseHandle (process_token);
-
-  _dbus_verbose("_dbus_getuid() returns %d\n",retval);
-  return retval;
-#endif
-}
-
-/**
- * The only reason this is separate from _dbus_getpid() is to allow it
- * on Windows for logging but not for other purposes.
- * 
- * @returns process ID to put in log messages
- */
-unsigned long
-_dbus_pid_for_log (void)
-{
-  return _dbus_getpid ();
-}
-
-
-
-#ifdef DBUS_BUILD_TESTS
-/** Gets our GID
- * @returns process GID
- */
-dbus_gid_t
-_dbus_getgid (void)
-{
-#ifndef ENABLE_UID_TO_SID
-       return DBUS_GID_UNSET;
-#else
-  dbus_gid_t retval = DBUS_GID_UNSET;
-  HANDLE process_token = NULL;
-  TOKEN_PRIMARY_GROUP *token_primary_group = NULL;
-  DWORD n;
-
-  if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
-    _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
-  else if ((!GetTokenInformation (process_token, TokenPrimaryGroup,
-                                  NULL, 0, &n) &&
-            GetLastError () != ERROR_INSUFFICIENT_BUFFER) ||
-           (token_primary_group = alloca (n)) == NULL ||
-           !GetTokenInformation (process_token, TokenPrimaryGroup,
-                                 token_primary_group, n, &n))
-    _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
-  else
-    retval = _dbus_win_sid_to_uid_t (token_primary_group->PrimaryGroup);
+    {
+      _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
+      goto failed;
+    }
+  psid = token_user->User.Sid;
+  if (!IsValidSid (psid))
+    {
+      _dbus_verbose("%s invalid sid\n",__FUNCTION__);
+      goto failed;
+    }
+  if (!ConvertSidToStringSidA (psid, sid))
+    {
+      _dbus_verbose("%s invalid sid\n",__FUNCTION__);
+      goto failed;
+    }
+//okay:
+  retval = TRUE;
 
-  if (process_token != NULL)
+failed:
+  CloseHandle (process_handle);
+  if (process_token != INVALID_HANDLE_VALUE)
     CloseHandle (process_token);
 
+  _dbus_verbose("_dbus_getsid() got '%s' and returns %d\n", *sid, retval);
   return retval;
-#endif
-}
-
-#if 0
-dbus_bool_t
-_dbus_domain_test (const char *test_data_dir)
-{
-  if (!_dbus_test_oom_handling ("spawn_nonexistent",
-                                check_spawn_nonexistent,
-                                NULL))
-    return FALSE;
 }
-
 #endif
 
-#endif //DBUS_BUILD_TESTS
-
 /************************************************************************
  
  pipes
@@ -1943,11 +1037,6 @@ _dbus_domain_test (const char *test_data_dir)
  * Creates a full-duplex pipe (as in socketpair()).
  * Sets both ends of the pipe nonblocking.
  *
- * @todo libdbus only uses this for the debug-pipe server, so in
- * principle it could be in dbus-sysdeps-util.c, except that
- * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
- * debug-pipe server is used.
- * 
  * @param fd1 return location for one end
  * @param fd2 return location for the other end
  * @param blocking #TRUE if pipe should be blocking
@@ -1964,12 +1053,6 @@ _dbus_full_duplex_pipe (int        *fd1,
   struct sockaddr_in saddr;
   int len;
   u_long arg;
-  fd_set read_set, write_set;
-  struct timeval tv;
-#ifdef ENABLE_DBUSSOCKET
-  DBusSocket sock;
-#endif
-
 
   _dbus_win_startup_winsock ();
 
@@ -1980,19 +1063,12 @@ _dbus_full_duplex_pipe (int        *fd1,
       goto out0;
     }
 
-  arg = 1;
-  if (ioctlsocket (temp, FIONBIO, &arg) == SOCKET_ERROR)
-    {
-      DBUS_SOCKET_SET_ERRNO ();
-      goto out0;
-    }
-
   _DBUS_ZERO (saddr);
   saddr.sin_family = AF_INET;
   saddr.sin_port = 0;
   saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
 
-  if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
+  if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)) == SOCKET_ERROR)
     {
       DBUS_SOCKET_SET_ERRNO ();
       goto out0;
@@ -2005,7 +1081,7 @@ _dbus_full_duplex_pipe (int        *fd1,
     }
 
   len = sizeof (saddr);
-  if (getsockname (temp, (struct sockaddr *)&saddr, &len))
+  if (getsockname (temp, (struct sockaddr *)&saddr, &len) == SOCKET_ERROR)
     {
       DBUS_SOCKET_SET_ERRNO ();
       goto out0;
@@ -2018,34 +1094,12 @@ _dbus_full_duplex_pipe (int        *fd1,
       goto out0;
     }
 
-  arg = 1;
-  if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
-    {
-      DBUS_SOCKET_SET_ERRNO ();
-      goto out1;
-    }
-
-  if (connect (socket1, (struct sockaddr  *)&saddr, len) != SOCKET_ERROR ||
-      WSAGetLastError () != WSAEWOULDBLOCK)
-    {
-      DBUS_SOCKET_SET_ERRNO ();
-      goto out1;
-    }
-
-  FD_ZERO (&read_set);
-  FD_SET (temp, &read_set);
-
-  tv.tv_sec = 0;
-  tv.tv_usec = 0;
-
-  if (select (0, &read_set, NULL, NULL, NULL) == SOCKET_ERROR)
+  if (connect (socket1, (struct sockaddr  *)&saddr, len) == SOCKET_ERROR)
     {
       DBUS_SOCKET_SET_ERRNO ();
       goto out1;
     }
 
-  _dbus_assert (FD_ISSET (temp, &read_set));
-
   socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
   if (socket2 == INVALID_SOCKET)
     {
@@ -2053,38 +1107,15 @@ _dbus_full_duplex_pipe (int        *fd1,
       goto out1;
     }
 
-  FD_ZERO (&write_set);
-  FD_SET (socket1, &write_set);
-
-  tv.tv_sec = 0;
-  tv.tv_usec = 0;
-
-  if (select (0, NULL, &write_set, NULL, NULL) == SOCKET_ERROR)
-    {
-      DBUS_SOCKET_SET_ERRNO ();
-      goto out2;
-    }
-
-  _dbus_assert (FD_ISSET (socket1, &write_set));
-
-  if (blocking)
+  if (!blocking)
     {
-      arg = 0;
+      arg = 1;
       if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
         {
           DBUS_SOCKET_SET_ERRNO ();
           goto out2;
         }
 
-      arg = 0;
-      if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
-        {
-          DBUS_SOCKET_SET_ERRNO ();
-          goto out2;
-        }
-    }
-  else
-    {
       arg = 1;
       if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
         {
@@ -2093,15 +1124,8 @@ _dbus_full_duplex_pipe (int        *fd1,
         }
     }
 
-#ifdef ENABLE_DBUSSOCKET
-  sock.fd = socket1;
-  *fd1 = _dbus_socket_to_handle (&sock);
-  sock.fd = socket2;
-  *fd2 = _dbus_socket_to_handle (&sock);
-#else
   *fd1 = socket1;
   *fd2 = socket2;
-#endif
 
   _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
                  *fd1, socket1, *fd2, socket2);
@@ -2119,7 +1143,7 @@ out0:
 
   dbus_set_error (error, _dbus_error_from_errno (errno),
                   "Could not setup socket pair: %s",
-                  _dbus_strerror (errno));
+                  _dbus_strerror_from_errno ());
 
   return FALSE;
 }
@@ -2132,13 +1156,15 @@ out0:
  * @param timeout_milliseconds timeout or -1 for infinite
  * @returns numbers of fds with revents, or <0 on error
  */
-#define USE_CHRIS_IMPL 0
-#if USE_CHRIS_IMPL
 int
 _dbus_poll (DBusPollFD *fds,
             int         n_fds,
             int         timeout_milliseconds)
 {
+#define USE_CHRIS_IMPL 0
+
+#if USE_CHRIS_IMPL
+
 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
   char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
   char *msgp;
@@ -2156,32 +1182,22 @@ _dbus_poll (DBusPollFD *fds,
   else
     pEvents = eventsOnStack;
 
-  _dbus_lock_sockets();
 
 #ifdef DBUS_ENABLE_VERBOSE_MODE
   msgp = msg;
   msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
   for (i = 0; i < n_fds; i++)
     {
-      static dbus_bool_t warned = FALSE;
-      DBusSocket *s;
       DBusPollFD *fdp = &fds[i];
 
-      _dbus_handle_to_socket_unlocked(fdp->fd, &s);  
-
-      if (s->is_used == 0)
-        {
-          _dbus_warn ("no valid socket");
-          warned = TRUE;
-        }
 
       if (fdp->events & _DBUS_POLLIN)
-        msgp += sprintf (msgp, "R:%d ", s->fd);
+        msgp += sprintf (msgp, "R:%d ", fdp->fd);
 
       if (fdp->events & _DBUS_POLLOUT)
-        msgp += sprintf (msgp, "W:%d ", s->fd);
+        msgp += sprintf (msgp, "W:%d ", fdp->fd);
 
-      msgp += sprintf (msgp, "E:%d\n\t", s->fd);
+      msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
 
       // FIXME: more robust code for long  msg
       //        create on heap when msg[] becomes too small
@@ -2196,16 +1212,10 @@ _dbus_poll (DBusPollFD *fds,
 #endif
   for (i = 0; i < n_fds; i++)
     {
-      DBusSocket *s;
       DBusPollFD *fdp = &fds[i];
       WSAEVENT ev;
       long lNetworkEvents = FD_OOB;
 
-      _dbus_handle_to_socket_unlocked(fdp->fd, &s); 
-
-      if (s->is_used == 0)
-        continue;
-
       ev = WSACreateEvent();
 
       if (fdp->events & _DBUS_POLLIN)
@@ -2214,20 +1224,19 @@ _dbus_poll (DBusPollFD *fds,
       if (fdp->events & _DBUS_POLLOUT)
         lNetworkEvents |= FD_WRITE | FD_CONNECT;
 
-      WSAEventSelect(s->fd, ev, lNetworkEvents);
+      WSAEventSelect(fdp->fd, ev, lNetworkEvents);
 
       pEvents[i] = ev;
     }
 
-  _dbus_unlock_sockets();
 
   ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
 
   if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
     {
       DBUS_SOCKET_SET_ERRNO ();
-      if (errno != EWOULDBLOCK)
-        _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror (errno));
+      if (errno != WSAEWOULDBLOCK)
+        _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror_from_errno ());
       ret = -1;
     }
   else if (ready == WSA_WAIT_TIMEOUT)
@@ -2240,18 +1249,14 @@ _dbus_poll (DBusPollFD *fds,
       msgp = msg;
       msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
 
-      _dbus_lock_sockets();
       for (i = 0; i < n_fds; i++)
         {
-          DBusSocket *s;
           DBusPollFD *fdp = &fds[i];
           WSANETWORKEVENTS ne;
 
-          _dbus_handle_to_socket_unlocked(fdp->fd, &s); 
-
           fdp->revents = 0;
 
-          WSAEnumNetworkEvents(s->fd, pEvents[i], &ne);
+          WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
 
           if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
             fdp->revents |= _DBUS_POLLIN;
@@ -2263,22 +1268,21 @@ _dbus_poll (DBusPollFD *fds,
             fdp->revents |= _DBUS_POLLERR;
 
           if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
-              msgp += sprintf (msgp, "R:%d ", s->fd);
+              msgp += sprintf (msgp, "R:%d ", fdp->fd);
 
           if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
-              msgp += sprintf (msgp, "W:%d ", s->fd);
+              msgp += sprintf (msgp, "W:%d ", fdp->fd);
 
           if (ne.lNetworkEvents & (FD_OOB))
-              msgp += sprintf (msgp, "E:%d ", s->fd);
+              msgp += sprintf (msgp, "E:%d ", fdp->fd);
 
           msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
 
           if(ne.lNetworkEvents)
             ret++;
 
-          WSAEventSelect(s->fd, pEvents[i], 0);
+          WSAEventSelect(fdp->fd, pEvents[i], 0);
         }
-      _dbus_unlock_sockets();
 
       msgp += sprintf (msgp, "\n");
       _dbus_verbose ("%s",msg);
@@ -2298,17 +1302,9 @@ _dbus_poll (DBusPollFD *fds,
     free(pEvents);
 
   return ret;
-}
 
-#else   // USE_CHRIS_IMPL
+#else   /* USE_CHRIS_IMPL */
 
-#ifdef ENABLE_DBUSSOCKET
-
-int
-_dbus_poll (DBusPollFD *fds,
-            int         n_fds,
-            int         timeout_milliseconds)
-{
 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
   char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
   char *msgp;
@@ -2323,32 +1319,22 @@ _dbus_poll (DBusPollFD *fds,
   FD_ZERO (&write_set);
   FD_ZERO (&err_set);
 
-  _dbus_lock_sockets();
 
 #ifdef DBUS_ENABLE_VERBOSE_MODE
   msgp = msg;
   msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
   for (i = 0; i < n_fds; i++)
     {
-      static dbus_bool_t warned = FALSE;
-      DBusSocket *s;
       DBusPollFD *fdp = &fds[i];
 
-      _dbus_handle_to_socket_unlocked(fdp->fd, &s);  
-
-      if (s->is_used == 0)
-        {
-          _dbus_warn ("no valid socket");
-          warned = TRUE;
-        }
 
       if (fdp->events & _DBUS_POLLIN)
-        msgp += sprintf (msgp, "R:%d ", s->fd);
+        msgp += sprintf (msgp, "R:%d ", fdp->fd);
 
       if (fdp->events & _DBUS_POLLOUT)
-        msgp += sprintf (msgp, "W:%d ", s->fd);
+        msgp += sprintf (msgp, "W:%d ", fdp->fd);
 
-      msgp += sprintf (msgp, "E:%d\n\t", s->fd);
+      msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
 
       // FIXME: more robust code for long  msg
       //        create on heap when msg[] becomes too small
@@ -2363,38 +1349,30 @@ _dbus_poll (DBusPollFD *fds,
 #endif
   for (i = 0; i < n_fds; i++)
     {
-      DBusSocket *s;
-      DBusPollFD *fdp = &fds[i];
-
-      _dbus_handle_to_socket_unlocked(fdp->fd, &s); 
-
-      if (s->is_used != 1)
-        continue;
+      DBusPollFD *fdp = &fds[i]; 
 
       if (fdp->events & _DBUS_POLLIN)
-        FD_SET (s->fd, &read_set);
+        FD_SET (fdp->fd, &read_set);
 
       if (fdp->events & _DBUS_POLLOUT)
-        FD_SET (s->fd, &write_set);
+        FD_SET (fdp->fd, &write_set);
 
-      FD_SET (s->fd, &err_set);
+      FD_SET (fdp->fd, &err_set);
 
-      max_fd = MAX (max_fd, s->fd);
+      max_fd = MAX (max_fd, fdp->fd);
     }
 
-  _dbus_unlock_sockets();
+  // Avoid random lockups with send(), for lack of a better solution so far
+  tv.tv_sec = timeout_milliseconds < 0 ? 1 : timeout_milliseconds / 1000;
+  tv.tv_usec = timeout_milliseconds < 0 ? 0 : (timeout_milliseconds % 1000) * 1000;
 
-  tv.tv_sec = timeout_milliseconds / 1000;
-  tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
-
-  ready = select (max_fd + 1, &read_set, &write_set, &err_set,
-                  timeout_milliseconds < 0 ? NULL : &tv);
+  ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
 
   if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
     {
       DBUS_SOCKET_SET_ERRNO ();
-      if (errno != EWOULDBLOCK)
-        _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
+      if (errno != WSAEWOULDBLOCK)
+        _dbus_verbose ("select: failed: %s\n", _dbus_strerror_from_errno ());
     }
   else if (ready == 0)
     _dbus_verbose ("select: = 0\n");
@@ -2404,22 +1382,19 @@ _dbus_poll (DBusPollFD *fds,
 #ifdef DBUS_ENABLE_VERBOSE_MODE
         msgp = msg;
         msgp += sprintf (msgp, "select: = %d:\n\t", ready);
-        _dbus_lock_sockets();
+
         for (i = 0; i < n_fds; i++)
           {
-            DBusSocket *s;
             DBusPollFD *fdp = &fds[i];
 
-            _dbus_handle_to_socket_unlocked(fdp->fd, &s); 
+            if (FD_ISSET (fdp->fd, &read_set))
+              msgp += sprintf (msgp, "R:%d ", fdp->fd);
 
-            if (FD_ISSET (s->fd, &read_set))
-              msgp += sprintf (msgp, "R:%d ", s->fd);
+            if (FD_ISSET (fdp->fd, &write_set))
+              msgp += sprintf (msgp, "W:%d ", fdp->fd);
 
-            if (FD_ISSET (s->fd, &write_set))
-              msgp += sprintf (msgp, "W:%d ", s->fd);
-
-            if (FD_ISSET (s->fd, &err_set))
-              msgp += sprintf (msgp, "E:%d\n\t", s->fd);
+            if (FD_ISSET (fdp->fd, &err_set))
+              msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
           }
         msgp += sprintf (msgp, "\n");
         _dbus_verbose ("%s",msg);
@@ -2427,1431 +1402,408 @@ _dbus_poll (DBusPollFD *fds,
 
         for (i = 0; i < n_fds; i++)
           {
-            DBusSocket *s;
             DBusPollFD *fdp = &fds[i];
 
-            _dbus_handle_to_socket_unlocked(fdp->fd, &s); 
-
             fdp->revents = 0;
 
-            if (FD_ISSET (s->fd, &read_set))
+            if (FD_ISSET (fdp->fd, &read_set))
               fdp->revents |= _DBUS_POLLIN;
 
-            if (FD_ISSET (s->fd, &write_set))
+            if (FD_ISSET (fdp->fd, &write_set))
               fdp->revents |= _DBUS_POLLOUT;
 
-            if (FD_ISSET (s->fd, &err_set))
+            if (FD_ISSET (fdp->fd, &err_set))
               fdp->revents |= _DBUS_POLLERR;
           }
-        _dbus_unlock_sockets();
       }
   return ready;
+#endif  /* USE_CHRIS_IMPL */
 }
-#else // ENABLE_DBUSSOCKET
 
-int
-_dbus_poll (DBusPollFD *fds,
-            int         n_fds,
-            int         timeout_milliseconds)
-{
-#define DBUS_POLL_CHAR_BUFFER_SIZE 2000
-  char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
-  char *msgp;
 
-  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);
 
+/******************************************************************************
+Original CVS version of dbus-sysdeps.c
+******************************************************************************/
+/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
+/* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
+ * 
+ * Copyright (C) 2002, 2003  Red Hat, Inc.
+ * Copyright (C) 2003 CodeFactory AB
+ * Copyright (C) 2005 Novell, Inc.
+ *
+ * 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
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ *
+ */
 
-#ifdef DBUS_ENABLE_VERBOSE_MODE
-  msgp = msg;
-  msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
-  for (i = 0; i < n_fds; i++)
-    {
-      static dbus_bool_t warned = FALSE;
-      int fd;
-      DBusPollFD *fdp = &fds[i];
-      fd = fdp->fd;  
 
+/**
+ * Exit the process, returning the given value.
+ *
+ * @param code the exit code
+ */
+void
+_dbus_exit (int code)
+{
+  _exit (code);
+}
 
-      if (fdp->events & _DBUS_POLLIN)
-        msgp += sprintf (msgp, "R:%d ", fd);
+/**
+ * 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 port to connect to
+ * @param family the address family to listen on, NULL for all
+ * @param error return location for error code
+ * @returns connection file descriptor or -1 on error
+ */
+int
+_dbus_connect_tcp_socket (const char     *host,
+                          const char     *port,
+                          const char     *family,
+                          DBusError      *error)
+{
+  return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
+}
 
-      if (fdp->events & _DBUS_POLLOUT)
-        msgp += sprintf (msgp, "W:%d ", fd);
+int
+_dbus_connect_tcp_socket_with_nonce (const char     *host,
+                                     const char     *port,
+                                     const char     *family,
+                                     const char     *noncefile,
+                                     DBusError      *error)
+{
+  int fd = -1, res;
+  struct addrinfo hints;
+  struct addrinfo *ai, *tmp;
 
-      msgp += sprintf (msgp, "E:%d\n\t", fd);
+  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
 
-      // FIXME: more robust code for long  msg
-      //        create on heap when msg[] becomes too small
-      if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
-        {
-          _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
-        }
-    }
+  _dbus_win_startup_winsock ();
 
-  msgp += sprintf (msgp, "\n");
-  _dbus_verbose ("%s",msg);
-#endif
-  for (i = 0; i < n_fds; i++)
-    {
-        int fd;
-      DBusPollFD *fdp = &fds[i];
-      fd = fdp->fd;  
-
-      if (fdp->events & _DBUS_POLLIN)
-        FD_SET (fd, &read_set);
-
-      if (fdp->events & _DBUS_POLLOUT)
-        FD_SET (fd, &write_set);
-
-      FD_SET (fd, &err_set);
+  _DBUS_ZERO (hints);
 
-      max_fd = MAX (max_fd, 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,
-                  timeout_milliseconds < 0 ? NULL : &tv);
-
-  if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
-    {
-      DBUS_SOCKET_SET_ERRNO ();
-      if (errno != EWOULDBLOCK)
-        _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
-    }
-  else if (ready == 0)
-    _dbus_verbose ("select: = 0\n");
+  if (!family)
+    hints.ai_family = AF_UNSPEC;
+  else if (!strcmp(family, "ipv4"))
+    hints.ai_family = AF_INET;
+  else if (!strcmp(family, "ipv6"))
+    hints.ai_family = AF_INET6;
   else
-    if (ready > 0)
-      {
-#ifdef DBUS_ENABLE_VERBOSE_MODE
-        msgp = msg;
-        msgp += sprintf (msgp, "select: = %d:\n\t", ready);
-
-        for (i = 0; i < n_fds; i++)
-          {
-            int fd;
-            DBusPollFD *fdp = &fds[i];
-            fd = fdp->fd;  
-
-            if (FD_ISSET (fd, &read_set))
-              msgp += sprintf (msgp, "R:%d ", fd);
-
-            if (FD_ISSET (fd, &write_set))
-              msgp += sprintf (msgp, "W:%d ", fd);
-
-            if (FD_ISSET (fd, &err_set))
-              msgp += sprintf (msgp, "E:%d\n\t", fd);
-          }
-        msgp += sprintf (msgp, "\n");
-        _dbus_verbose ("%s",msg);
-#endif
-
-        for (i = 0; i < n_fds; i++)
-          {
-            int fd;
-            DBusPollFD *fdp = &fds[i];
-            fd = fdp->fd;  
-
-            fdp->revents = 0;
-
-            if (FD_ISSET (fd, &read_set))
-              fdp->revents |= _DBUS_POLLIN;
-
-            if (FD_ISSET (fd, &write_set))
-              fdp->revents |= _DBUS_POLLOUT;
-
-            if (FD_ISSET (fd, &err_set))
-              fdp->revents |= _DBUS_POLLERR;
-          }
-      }
-  return ready;
-}
-
-#endif  //ENABLE_DBUSSOCKET
-
-#endif  // USE_CHRIS_IMPL
-
-
-/************************************************************************
- error handling
- ************************************************************************/
-
-
-/**
- * Assigns an error name and message corresponding to a Win32 error
- * code to a DBusError. Does nothing if error is #NULL.
- *
- * @param error the error.
- * @param code the Win32 error code
- */
-void
-_dbus_win_set_error_from_win_error (DBusError *error,
-                                    int        code)
-{
-  char *msg;
-
-  /* As we want the English message, use the A API */
-  FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
-                  FORMAT_MESSAGE_IGNORE_INSERTS |
-                  FORMAT_MESSAGE_FROM_SYSTEM,
-                  NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
-                  (LPTSTR) &msg, 0, NULL);
-  if (msg)
-    {
-      char *msg_copy;
-
-      msg_copy = dbus_malloc (strlen (msg));
-      strcpy (msg_copy, msg);
-      LocalFree (msg);
-
-      dbus_set_error (error, "win32.error", "%s", msg_copy);
-    }
-  else
-    dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
-}
-
-void
-_dbus_win_warn_win_error (const char *message,
-                          int         code)
-{
-  DBusError error;
-
-  dbus_error_init (&error);
-  _dbus_win_set_error_from_win_error (&error, code);
-  _dbus_warn ("%s: %s\n", message, error.message);
-  dbus_error_free (&error);
-}
-
-/**
- * A wrapper around strerror() because some platforms
- * may be lame and not have strerror().
- *
- * @param error_number errno.
- * @returns error description.
- */
-const char*
-_dbus_strerror (int error_number)
-{
-#ifdef DBUS_WINCE
-  // TODO
-  return "unknown";
-#else
-  const char *msg;
-
-  switch (error_number)
     {
-    case WSAEINTR:
-      return "Interrupted function call";
-    case WSAEACCES:
-      return "Permission denied";
-    case WSAEFAULT:
-      return "Bad address";
-    case WSAEINVAL:
-      return "Invalid argument";
-    case WSAEMFILE:
-      return "Too many open files";
-    case WSAEWOULDBLOCK:
-      return "Resource temporarily unavailable";
-    case WSAEINPROGRESS:
-      return "Operation now in progress";
-    case WSAEALREADY:
-      return "Operation already in progress";
-    case WSAENOTSOCK:
-      return "Socket operation on nonsocket";
-    case WSAEDESTADDRREQ:
-      return "Destination address required";
-    case WSAEMSGSIZE:
-      return "Message too long";
-    case WSAEPROTOTYPE:
-      return "Protocol wrong type for socket";
-    case WSAENOPROTOOPT:
-      return "Bad protocol option";
-    case WSAEPROTONOSUPPORT:
-      return "Protocol not supported";
-    case WSAESOCKTNOSUPPORT:
-      return "Socket type not supported";
-    case WSAEOPNOTSUPP:
-      return "Operation not supported";
-    case WSAEPFNOSUPPORT:
-      return "Protocol family not supported";
-    case WSAEAFNOSUPPORT:
-      return "Address family not supported by protocol family";
-    case WSAEADDRINUSE:
-      return "Address already in use";
-    case WSAEADDRNOTAVAIL:
-      return "Cannot assign requested address";
-    case WSAENETDOWN:
-      return "Network is down";
-    case WSAENETUNREACH:
-      return "Network is unreachable";
-    case WSAENETRESET:
-      return "Network dropped connection on reset";
-    case WSAECONNABORTED:
-      return "Software caused connection abort";
-    case WSAECONNRESET:
-      return "Connection reset by peer";
-    case WSAENOBUFS:
-      return "No buffer space available";
-    case WSAEISCONN:
-      return "Socket is already connected";
-    case WSAENOTCONN:
-      return "Socket is not connected";
-    case WSAESHUTDOWN:
-      return "Cannot send after socket shutdown";
-    case WSAETIMEDOUT:
-      return "Connection timed out";
-    case WSAECONNREFUSED:
-      return "Connection refused";
-    case WSAEHOSTDOWN:
-      return "Host is down";
-    case WSAEHOSTUNREACH:
-      return "No route to host";
-    case WSAEPROCLIM:
-      return "Too many processes";
-    case WSAEDISCON:
-      return "Graceful shutdown in progress";
-    case WSATYPE_NOT_FOUND:
-      return "Class type not found";
-    case WSAHOST_NOT_FOUND:
-      return "Host not found";
-    case WSATRY_AGAIN:
-      return "Nonauthoritative host not found";
-    case WSANO_RECOVERY:
-      return "This is a nonrecoverable error";
-    case WSANO_DATA:
-      return "Valid name, no data record of requested type";
-    case WSA_INVALID_HANDLE:
-      return "Specified event object handle is invalid";
-    case WSA_INVALID_PARAMETER:
-      return "One or more parameters are invalid";
-    case WSA_IO_INCOMPLETE:
-      return "Overlapped I/O event object not in signaled state";
-    case WSA_IO_PENDING:
-      return "Overlapped operations will complete later";
-    case WSA_NOT_ENOUGH_MEMORY:
-      return "Insufficient memory available";
-    case WSA_OPERATION_ABORTED:
-      return "Overlapped operation aborted";
-#ifdef WSAINVALIDPROCTABLE
-
-    case WSAINVALIDPROCTABLE:
-      return "Invalid procedure table from service provider";
-#endif
-#ifdef WSAINVALIDPROVIDER
-
-    case WSAINVALIDPROVIDER:
-      return "Invalid service provider version number";
-#endif
-#ifdef WSAPROVIDERFAILEDINIT
-
-    case WSAPROVIDERFAILEDINIT:
-      return "Unable to initialize a service provider";
-#endif
-
-    case WSASYSCALLFAILURE:
-      return "System call failure";
-    }
-  msg = strerror (error_number);
-  if (msg == NULL)
-    msg = "unknown";
-
-  return msg;
-#endif //DBUS_WINCE
-}
-
-
-
-/* lan manager error codes */
-const char*
-_dbus_lm_strerror(int error_number)
-{
-#ifdef DBUS_WINCE
-  // TODO
-  return "unknown";
-#else
-  const char *msg;
-  switch (error_number)
-    {
-    case NERR_NetNotStarted:
-      return "The workstation driver is not installed.";
-    case NERR_UnknownServer:
-      return "The server could not be located.";
-    case NERR_ShareMem:
-      return "An internal error occurred. The network cannot access a shared memory segment.";
-    case NERR_NoNetworkResource:
-      return "A network resource shortage occurred.";
-    case NERR_RemoteOnly:
-      return "This operation is not supported on workstations.";
-    case NERR_DevNotRedirected:
-      return "The device is not connected.";
-    case NERR_ServerNotStarted:
-      return "The Server service is not started.";
-    case NERR_ItemNotFound:
-      return "The queue is empty.";
-    case NERR_UnknownDevDir:
-      return "The device or directory does not exist.";
-    case NERR_RedirectedPath:
-      return "The operation is invalid on a redirected resource.";
-    case NERR_DuplicateShare:
-      return "The name has already been shared.";
-    case NERR_NoRoom:
-      return "The server is currently out of the requested resource.";
-    case NERR_TooManyItems:
-      return "Requested addition of items exceeds the maximum allowed.";
-    case NERR_InvalidMaxUsers:
-      return "The Peer service supports only two simultaneous users.";
-    case NERR_BufTooSmall:
-      return "The API return buffer is too small.";
-    case NERR_RemoteErr:
-      return "A remote API error occurred.";
-    case NERR_LanmanIniError:
-      return "An error occurred when opening or reading the configuration file.";
-    case NERR_NetworkError:
-      return "A general network error occurred.";
-    case NERR_WkstaInconsistentState:
-      return "The Workstation service is in an inconsistent state. Restart the computer before restarting the Workstation service.";
-    case NERR_WkstaNotStarted:
-      return "The Workstation service has not been started.";
-    case NERR_BrowserNotStarted:
-      return "The requested information is not available.";
-    case NERR_InternalError:
-      return "An internal error occurred.";
-    case NERR_BadTransactConfig:
-      return "The server is not configured for transactions.";
-    case NERR_InvalidAPI:
-      return "The requested API is not supported on the remote server.";
-    case NERR_BadEventName:
-      return "The event name is invalid.";
-    case NERR_DupNameReboot:
-      return "The computer name already exists on the network. Change it and restart the computer.";
-    case NERR_CfgCompNotFound:
-      return "The specified component could not be found in the configuration information.";
-    case NERR_CfgParamNotFound:
-      return "The specified parameter could not be found in the configuration information.";
-    case NERR_LineTooLong:
-      return "A line in the configuration file is too long.";
-    case NERR_QNotFound:
-      return "The printer does not exist.";
-    case NERR_JobNotFound:
-      return "The print job does not exist.";
-    case NERR_DestNotFound:
-      return "The printer destination cannot be found.";
-    case NERR_DestExists:
-      return "The printer destination already exists.";
-    case NERR_QExists:
-      return "The printer queue already exists.";
-    case NERR_QNoRoom:
-      return "No more printers can be added.";
-    case NERR_JobNoRoom:
-      return "No more print jobs can be added.";
-    case NERR_DestNoRoom:
-      return "No more printer destinations can be added.";
-    case NERR_DestIdle:
-      return "This printer destination is idle and cannot accept control operations.";
-    case NERR_DestInvalidOp:
-      return "This printer destination request contains an invalid control function.";
-    case NERR_ProcNoRespond:
-      return "The print processor is not responding.";
-    case NERR_SpoolerNotLoaded:
-      return "The spooler is not running.";
-    case NERR_DestInvalidState:
-      return "This operation cannot be performed on the print destination in its current state.";
-    case NERR_QInvalidState:
-      return "This operation cannot be performed on the printer queue in its current state.";
-    case NERR_JobInvalidState:
-      return "This operation cannot be performed on the print job in its current state.";
-    case NERR_SpoolNoMemory:
-      return "A spooler memory allocation failure occurred.";
-    case NERR_DriverNotFound:
-      return "The device driver does not exist.";
-    case NERR_DataTypeInvalid:
-      return "The data type is not supported by the print processor.";
-    case NERR_ProcNotFound:
-      return "The print processor is not installed.";
-    case NERR_ServiceTableLocked:
-      return "The service database is locked.";
-    case NERR_ServiceTableFull:
-      return "The service table is full.";
-    case NERR_ServiceInstalled:
-      return "The requested service has already been started.";
-    case NERR_ServiceEntryLocked:
-      return "The service does not respond to control actions.";
-    case NERR_ServiceNotInstalled:
-      return "The service has not been started.";
-    case NERR_BadServiceName:
-      return "The service name is invalid.";
-    case NERR_ServiceCtlTimeout:
-      return "The service is not responding to the control function.";
-    case NERR_ServiceCtlBusy:
-      return "The service control is busy.";
-    case NERR_BadServiceProgName:
-      return "The configuration file contains an invalid service program name.";
-    case NERR_ServiceNotCtrl:
-      return "The service could not be controlled in its present state.";
-    case NERR_ServiceKillProc:
-      return "The service ended abnormally.";
-    case NERR_ServiceCtlNotValid:
-      return "The requested pause or stop is not valid for this service.";
-    case NERR_NotInDispatchTbl:
-      return "The service control dispatcher could not find the service name in the dispatch table.";
-    case NERR_BadControlRecv:
-      return "The service control dispatcher pipe read failed.";
-    case NERR_ServiceNotStarting:
-      return "A thread for the new service could not be created.";
-    case NERR_AlreadyLoggedOn:
-      return "This workstation is already logged on to the local-area network.";
-    case NERR_NotLoggedOn:
-      return "The workstation is not logged on to the local-area network.";
-    case NERR_BadUsername:
-      return "The user name or group name parameter is invalid.";
-    case NERR_BadPassword:
-      return "The password parameter is invalid.";
-    case NERR_UnableToAddName_W:
-      return "@W The logon processor did not add the message alias.";
-    case NERR_UnableToAddName_F:
-      return "The logon processor did not add the message alias.";
-    case NERR_UnableToDelName_W:
-      return "@W The logoff processor did not delete the message alias.";
-    case NERR_UnableToDelName_F:
-      return "The logoff processor did not delete the message alias.";
-    case NERR_LogonsPaused:
-      return "Network logons are paused.";
-    case NERR_LogonServerConflict:
-      return "A centralized logon-server conflict occurred.";
-    case NERR_LogonNoUserPath:
-      return "The server is configured without a valid user path.";
-    case NERR_LogonScriptError:
-      return "An error occurred while loading or running the logon script.";
-    case NERR_StandaloneLogon:
-      return "The logon server was not specified. Your computer will be logged on as STANDALONE.";
-    case NERR_LogonServerNotFound:
-      return "The logon server could not be found.";
-    case NERR_LogonDomainExists:
-      return "There is already a logon domain for this computer.";
-    case NERR_NonValidatedLogon:
-      return "The logon server could not validate the logon.";
-    case NERR_ACFNotFound:
-      return "The security database could not be found.";
-    case NERR_GroupNotFound:
-      return "The group name could not be found.";
-    case NERR_UserNotFound:
-      return "The user name could not be found.";
-    case NERR_ResourceNotFound:
-      return "The resource name could not be found.";
-    case NERR_GroupExists:
-      return "The group already exists.";
-    case NERR_UserExists:
-      return "The user account already exists.";
-    case NERR_ResourceExists:
-      return "The resource permission list already exists.";
-    case NERR_NotPrimary:
-      return "This operation is only allowed on the primary domain controller of the domain.";
-    case NERR_ACFNotLoaded:
-      return "The security database has not been started.";
-    case NERR_ACFNoRoom:
-      return "There are too many names in the user accounts database.";
-    case NERR_ACFFileIOFail:
-      return "A disk I/O failure occurred.";
-    case NERR_ACFTooManyLists:
-      return "The limit of 64 entries per resource was exceeded.";
-    case NERR_UserLogon:
-      return "Deleting a user with a session is not allowed.";
-    case NERR_ACFNoParent:
-      return "The parent directory could not be located.";
-    case NERR_CanNotGrowSegment:
-      return "Unable to add to the security database session cache segment.";
-    case NERR_SpeGroupOp:
-      return "This operation is not allowed on this special group.";
-    case NERR_NotInCache:
-      return "This user is not cached in user accounts database session cache.";
-    case NERR_UserInGroup:
-      return "The user already belongs to this group.";
-    case NERR_UserNotInGroup:
-      return "The user does not belong to this group.";
-    case NERR_AccountUndefined:
-      return "This user account is undefined.";
-    case NERR_AccountExpired:
-      return "This user account has expired.";
-    case NERR_InvalidWorkstation:
-      return "The user is not allowed to log on from this workstation.";
-    case NERR_InvalidLogonHours:
-      return "The user is not allowed to log on at this time.";
-    case NERR_PasswordExpired:
-      return "The password of this user has expired.";
-    case NERR_PasswordCantChange:
-      return "The password of this user cannot change.";
-    case NERR_PasswordHistConflict:
-      return "This password cannot be used now.";
-    case NERR_PasswordTooShort:
-      return "The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements.";
-    case NERR_PasswordTooRecent:
-      return "The password of this user is too recent to change.";
-    case NERR_InvalidDatabase:
-      return "The security database is corrupted.";
-    case NERR_DatabaseUpToDate:
-      return "No updates are necessary to this replicant network/local security database.";
-    case NERR_SyncRequired:
-      return "This replicant database is outdated; synchronization is required.";
-    case NERR_UseNotFound:
-      return "The network connection could not be found.";
-    case NERR_BadAsgType:
-      return "This asg_type is invalid.";
-    case NERR_DeviceIsShared:
-      return "This device is currently being shared.";
-    case NERR_NoComputerName:
-      return "The computer name could not be added as a message alias. The name may already exist on the network.";
-    case NERR_MsgAlreadyStarted:
-      return "The Messenger service is already started.";
-    case NERR_MsgInitFailed:
-      return "The Messenger service failed to start.";
-    case NERR_NameNotFound:
-      return "The message alias could not be found on the network.";
-    case NERR_AlreadyForwarded:
-      return "This message alias has already been forwarded.";
-    case NERR_AddForwarded:
-      return "This message alias has been added but is still forwarded.";
-    case NERR_AlreadyExists:
-      return "This message alias already exists locally.";
-    case NERR_TooManyNames:
-      return "The maximum number of added message aliases has been exceeded.";
-    case NERR_DelComputerName:
-      return "The computer name could not be deleted.";
-    case NERR_LocalForward:
-      return "Messages cannot be forwarded back to the same workstation.";
-    case NERR_GrpMsgProcessor:
-      return "An error occurred in the domain message processor.";
-    case NERR_PausedRemote:
-      return "The message was sent, but the recipient has paused the Messenger service.";
-    case NERR_BadReceive:
-      return "The message was sent but not received.";
-    case NERR_NameInUse:
-      return "The message alias is currently in use. Try again later.";
-    case NERR_MsgNotStarted:
-      return "The Messenger service has not been started.";
-    case NERR_NotLocalName:
-      return "The name is not on the local computer.";
-    case NERR_NoForwardName:
-      return "The forwarded message alias could not be found on the network.";
-    case NERR_RemoteFull:
-      return "The message alias table on the remote station is full.";
-    case NERR_NameNotForwarded:
-      return "Messages for this alias are not currently being forwarded.";
-    case NERR_TruncatedBroadcast:
-      return "The broadcast message was truncated.";
-    case NERR_InvalidDevice:
-      return "This is an invalid device name.";
-    case NERR_WriteFault:
-      return "A write fault occurred.";
-    case NERR_DuplicateName:
-      return "A duplicate message alias exists on the network.";
-    case NERR_DeleteLater:
-      return "@W This message alias will be deleted later.";
-    case NERR_IncompleteDel:
-      return "The message alias was not successfully deleted from all networks.";
-    case NERR_MultipleNets:
-      return "This operation is not supported on computers with multiple networks.";
-    case NERR_NetNameNotFound:
-      return "This shared resource does not exist.";
-    case NERR_DeviceNotShared:
-      return "This device is not shared.";
-    case NERR_ClientNameNotFound:
-      return "A session does not exist with that computer name.";
-    case NERR_FileIdNotFound:
-      return "There is not an open file with that identification number.";
-    case NERR_ExecFailure:
-      return "A failure occurred when executing a remote administration command.";
-    case NERR_TmpFile:
-      return "A failure occurred when opening a remote temporary file.";
-    case NERR_TooMuchData:
-      return "The data returned from a remote administration command has been truncated to 64K.";
-    case NERR_DeviceShareConflict:
-      return "This device cannot be shared as both a spooled and a non-spooled resource.";
-    case NERR_BrowserTableIncomplete:
-      return "The information in the list of servers may be incorrect.";
-    case NERR_NotLocalDomain:
-      return "The computer is not active in this domain.";
-#ifdef NERR_IsDfsShare
-
-    case NERR_IsDfsShare:
-      return "The share must be removed from the Distributed File System before it can be deleted.";
-#endif
-
-    case NERR_DevInvalidOpCode:
-      return "The operation is invalid for this device.";
-    case NERR_DevNotFound:
-      return "This device cannot be shared.";
-    case NERR_DevNotOpen:
-      return "This device was not open.";
-    case NERR_BadQueueDevString:
-      return "This device name list is invalid.";
-    case NERR_BadQueuePriority:
-      return "The queue priority is invalid.";
-    case NERR_NoCommDevs:
-      return "There are no shared communication devices.";
-    case NERR_QueueNotFound:
-      return "The queue you specified does not exist.";
-    case NERR_BadDevString:
-      return "This list of devices is invalid.";
-    case NERR_BadDev:
-      return "The requested device is invalid.";
-    case NERR_InUseBySpooler:
-      return "This device is already in use by the spooler.";
-    case NERR_CommDevInUse:
-      return "This device is already in use as a communication device.";
-    case NERR_InvalidComputer:
-      return "This computer name is invalid.";
-    case NERR_MaxLenExceeded:
-      return "The string and prefix specified are too long.";
-    case NERR_BadComponent:
-      return "This path component is invalid.";
-    case NERR_CantType:
-      return "Could not determine the type of input.";
-    case NERR_TooManyEntries:
-      return "The buffer for types is not big enough.";
-    case NERR_ProfileFileTooBig:
-      return "Profile files cannot exceed 64K.";
-    case NERR_ProfileOffset:
-      return "The start offset is out of range.";
-    case NERR_ProfileCleanup:
-      return "The system cannot delete current connections to network resources.";
-    case NERR_ProfileUnknownCmd:
-      return "The system was unable to parse the command line in this file.";
-    case NERR_ProfileLoadErr:
-      return "An error occurred while loading the profile file.";
-    case NERR_ProfileSaveErr:
-      return "@W Errors occurred while saving the profile file. The profile was partially saved.";
-    case NERR_LogOverflow:
-      return "Log file %1 is full.";
-    case NERR_LogFileChanged:
-      return "This log file has changed between reads.";
-    case NERR_LogFileCorrupt:
-      return "Log file %1 is corrupt.";
-    case NERR_SourceIsDir:
-      return "The source path cannot be a directory.";
-    case NERR_BadSource:
-      return "The source path is illegal.";
-    case NERR_BadDest:
-      return "The destination path is illegal.";
-    case NERR_DifferentServers:
-      return "The source and destination paths are on different servers.";
-    case NERR_RunSrvPaused:
-      return "The Run server you requested is paused.";
-    case NERR_ErrCommRunSrv:
-      return "An error occurred when communicating with a Run server.";
-    case NERR_ErrorExecingGhost:
-      return "An error occurred when starting a background process.";
-    case NERR_ShareNotFound:
-      return "The shared resource you are connected to could not be found.";
-    case NERR_InvalidLana:
-      return "The LAN adapter number is invalid.";
-    case NERR_OpenFiles:
-      return "There are open files on the connection.";
-    case NERR_ActiveConns:
-      return "Active connections still exist.";
-    case NERR_BadPasswordCore:
-      return "This share name or password is invalid.";
-    case NERR_DevInUse:
-      return "The device is being accessed by an active process.";
-    case NERR_LocalDrive:
-      return "The drive letter is in use locally.";
-    case NERR_AlertExists:
-      return "The specified client is already registered for the specified event.";
-    case NERR_TooManyAlerts:
-      return "The alert table is full.";
-    case NERR_NoSuchAlert:
-      return "An invalid or nonexistent alert name was raised.";
-    case NERR_BadRecipient:
-      return "The alert recipient is invalid.";
-    case NERR_AcctLimitExceeded:
-      return "A user's session with this server has been deleted.";
-    case NERR_InvalidLogSeek:
-      return "The log file does not contain the requested record number.";
-    case NERR_BadUasConfig:
-      return "The user accounts database is not configured correctly.";
-    case NERR_InvalidUASOp:
-      return "This operation is not permitted when the Netlogon service is running.";
-    case NERR_LastAdmin:
-      return "This operation is not allowed on the last administrative account.";
-    case NERR_DCNotFound:
-      return "Could not find domain controller for this domain.";
-    case NERR_LogonTrackingError:
-      return "Could not set logon information for this user.";
-    case NERR_NetlogonNotStarted:
-      return "The Netlogon service has not been started.";
-    case NERR_CanNotGrowUASFile:
-      return "Unable to add to the user accounts database.";
-    case NERR_TimeDiffAtDC:
-      return "This server's clock is not synchronized with the primary domain controller's clock.";
-    case NERR_PasswordMismatch:
-      return "A password mismatch has been detected.";
-    case NERR_NoSuchServer:
-      return "The server identification does not specify a valid server.";
-    case NERR_NoSuchSession:
-      return "The session identification does not specify a valid session.";
-    case NERR_NoSuchConnection:
-      return "The connection identification does not specify a valid connection.";
-    case NERR_TooManyServers:
-      return "There is no space for another entry in the table of available servers.";
-    case NERR_TooManySessions:
-      return "The server has reached the maximum number of sessions it supports.";
-    case NERR_TooManyConnections:
-      return "The server has reached the maximum number of connections it supports.";
-    case NERR_TooManyFiles:
-      return "The server cannot open more files because it has reached its maximum number.";
-    case NERR_NoAlternateServers:
-      return "There are no alternate servers registered on this server.";
-    case NERR_TryDownLevel:
-      return "Try down-level (remote admin protocol) version of API instead.";
-    case NERR_UPSDriverNotStarted:
-      return "The UPS driver could not be accessed by the UPS service.";
-    case NERR_UPSInvalidConfig:
-      return "The UPS service is not configured correctly.";
-    case NERR_UPSInvalidCommPort:
-      return "The UPS service could not access the specified Comm Port.";
-    case NERR_UPSSignalAsserted:
-      return "The UPS indicated a line fail or low battery situation. Service not started.";
-    case NERR_UPSShutdownFailed:
-      return "The UPS service failed to perform a system shut down.";
-    case NERR_BadDosRetCode:
-      return "The program below returned an MS-DOS error code:";
-    case NERR_ProgNeedsExtraMem:
-      return "The program below needs more memory:";
-    case NERR_BadDosFunction:
-      return "The program below called an unsupported MS-DOS function:";
-    case NERR_RemoteBootFailed:
-      return "The workstation failed to boot.";
-    case NERR_BadFileCheckSum:
-      return "The file below is corrupt.";
-    case NERR_NoRplBootSystem:
-      return "No loader is specified in the boot-block definition file.";
-    case NERR_RplLoadrNetBiosErr:
-      return "NetBIOS returned an error:      The NCB and SMB are dumped above.";
-    case NERR_RplLoadrDiskErr:
-      return "A disk I/O error occurred.";
-    case NERR_ImageParamErr:
-      return "Image parameter substitution failed.";
-    case NERR_TooManyImageParams:
-      return "Too many image parameters cross disk sector boundaries.";
-    case NERR_NonDosFloppyUsed:
-      return "The image was not generated from an MS-DOS diskette formatted with /S.";
-    case NERR_RplBootRestart:
-      return "Remote boot will be restarted later.";
-    case NERR_RplSrvrCallFailed:
-      return "The call to the Remoteboot server failed.";
-    case NERR_CantConnectRplSrvr:
-      return "Cannot connect to the Remoteboot server.";
-    case NERR_CantOpenImageFile:
-      return "Cannot open image file on the Remoteboot server.";
-    case NERR_CallingRplSrvr:
-      return "Connecting to the Remoteboot server...";
-    case NERR_StartingRplBoot:
-      return "Connecting to the Remoteboot server...";
-    case NERR_RplBootServiceTerm:
-      return "Remote boot service was stopped; check the error log for the cause of the problem.";
-    case NERR_RplBootStartFailed:
-      return "Remote boot startup failed; check the error log for the cause of the problem.";
-    case NERR_RPL_CONNECTED:
-      return "A second connection to a Remoteboot resource is not allowed.";
-    case NERR_BrowserConfiguredToNotRun:
-      return "The browser service was configured with MaintainServerList=No.";
-    case NERR_RplNoAdaptersStarted:
-      return "Service failed to start since none of the network adapters started with this service.";
-    case NERR_RplBadRegistry:
-      return "Service failed to start due to bad startup information in the registry.";
-    case NERR_RplBadDatabase:
-      return "Service failed to start because its database is absent or corrupt.";
-    case NERR_RplRplfilesShare:
-      return "Service failed to start because RPLFILES share is absent.";
-    case NERR_RplNotRplServer:
-      return "Service failed to start because RPLUSER group is absent.";
-    case NERR_RplCannotEnum:
-      return "Cannot enumerate service records.";
-    case NERR_RplWkstaInfoCorrupted:
-      return "Workstation record information has been corrupted.";
-    case NERR_RplWkstaNotFound:
-      return "Workstation record was not found.";
-    case NERR_RplWkstaNameUnavailable:
-      return "Workstation name is in use by some other workstation.";
-    case NERR_RplProfileInfoCorrupted:
-      return "Profile record information has been corrupted.";
-    case NERR_RplProfileNotFound:
-      return "Profile record was not found.";
-    case NERR_RplProfileNameUnavailable:
-      return "Profile name is in use by some other profile.";
-    case NERR_RplProfileNotEmpty:
-      return "There are workstations using this profile.";
-    case NERR_RplConfigInfoCorrupted:
-      return "Configuration record information has been corrupted.";
-    case NERR_RplConfigNotFound:
-      return "Configuration record was not found.";
-    case NERR_RplAdapterInfoCorrupted:
-      return "Adapter ID record information has been corrupted.";
-    case NERR_RplInternal:
-      return "An internal service error has occurred.";
-    case NERR_RplVendorInfoCorrupted:
-      return "Vendor ID record information has been corrupted.";
-    case NERR_RplBootInfoCorrupted:
-      return "Boot block record information has been corrupted.";
-    case NERR_RplWkstaNeedsUserAcct:
-      return "The user account for this workstation record is missing.";
-    case NERR_RplNeedsRPLUSERAcct:
-      return "The RPLUSER local group could not be found.";
-    case NERR_RplBootNotFound:
-      return "Boot block record was not found.";
-    case NERR_RplIncompatibleProfile:
-      return "Chosen profile is incompatible with this workstation.";
-    case NERR_RplAdapterNameUnavailable:
-      return "Chosen network adapter ID is in use by some other workstation.";
-    case NERR_RplConfigNotEmpty:
-      return "There are profiles using this configuration.";
-    case NERR_RplBootInUse:
-      return "There are workstations, profiles, or configurations using this boot block.";
-    case NERR_RplBackupDatabase:
-      return "Service failed to backup Remoteboot database.";
-    case NERR_RplAdapterNotFound:
-      return "Adapter record was not found.";
-    case NERR_RplVendorNotFound:
-      return "Vendor record was not found.";
-    case NERR_RplVendorNameUnavailable:
-      return "Vendor name is in use by some other vendor record.";
-    case NERR_RplBootNameUnavailable:
-      return "(boot name, vendor ID) is in use by some other boot block record.";
-    case NERR_RplConfigNameUnavailable:
-      return "Configuration name is in use by some other configuration.";
-    case NERR_DfsInternalCorruption:
-      return "The internal database maintained by the Dfs service is corrupt.";
-    case NERR_DfsVolumeDataCorrupt:
-      return "One of the records in the internal Dfs database is corrupt.";
-    case NERR_DfsNoSuchVolume:
-      return "There is no DFS name whose entry path matches the input Entry Path.";
-    case NERR_DfsVolumeAlreadyExists:
-      return "A root or link with the given name already exists.";
-    case NERR_DfsAlreadyShared:
-      return "The server share specified is already shared in the Dfs.";
-    case NERR_DfsNoSuchShare:
-      return "The indicated server share does not support the indicated DFS namespace.";
-    case NERR_DfsNotALeafVolume:
-      return "The operation is not valid on this portion of the namespace.";
-    case NERR_DfsLeafVolume:
-      return "The operation is not valid on this portion of the namespace.";
-    case NERR_DfsVolumeHasMultipleServers:
-      return "The operation is ambiguous because the link has multiple servers.";
-    case NERR_DfsCantCreateJunctionPoint:
-      return "Unable to create a link.";
-    case NERR_DfsServerNotDfsAware:
-      return "The server is not Dfs Aware.";
-    case NERR_DfsBadRenamePath:
-      return "The specified rename target path is invalid.";
-    case NERR_DfsVolumeIsOffline:
-      return "The specified DFS link is offline.";
-    case NERR_DfsNoSuchServer:
-      return "The specified server is not a server for this link.";
-    case NERR_DfsCyclicalName:
-      return "A cycle in the Dfs name was detected.";
-    case NERR_DfsNotSupportedInServerDfs:
-      return "The operation is not supported on a server-based Dfs.";
-    case NERR_DfsDuplicateService:
-      return "This link is already supported by the specified server-share.";
-    case NERR_DfsCantRemoveLastServerShare:
-      return "Can't remove the last server-share supporting this root or link.";
-    case NERR_DfsVolumeIsInterDfs:
-      return "The operation is not supported for an Inter-DFS link.";
-    case NERR_DfsInconsistent:
-      return "The internal state of the Dfs Service has become inconsistent.";
-    case NERR_DfsServerUpgraded:
-      return "The Dfs Service has been installed on the specified server.";
-    case NERR_DfsDataIsIdentical:
-      return "The Dfs data being reconciled is identical.";
-    case NERR_DfsCantRemoveDfsRoot:
-      return "The DFS root cannot be deleted. Uninstall DFS if required.";
-    case NERR_DfsChildOrParentInDfs:
-      return "A child or parent directory of the share is already in a Dfs.";
-    case NERR_DfsInternalError:
-      return "Dfs internal error.";
-      /* the following are not defined in mingw */
-#if 0
-
-    case NERR_SetupAlreadyJoined:
-      return "This machine is already joined to a domain.";
-    case NERR_SetupNotJoined:
-      return "This machine is not currently joined to a domain.";
-    case NERR_SetupDomainController:
-      return "This machine is a domain controller and cannot be unjoined from a domain.";
-    case NERR_DefaultJoinRequired:
-      return "The destination domain controller does not support creating machine accounts in OUs.";
-    case NERR_InvalidWorkgroupName:
-      return "The specified workgroup name is invalid.";
-    case NERR_NameUsesIncompatibleCodePage:
-      return "The specified computer name is incompatible with the default language used on the domain controller.";
-    case NERR_ComputerAccountNotFound:
-      return "The specified computer account could not be found.";
-    case NERR_PersonalSku:
-      return "This version of Windows cannot be joined to a domain.";
-    case NERR_PasswordMustChange:
-      return "The password must change at the next logon.";
-    case NERR_AccountLockedOut:
-      return "The account is locked out.";
-    case NERR_PasswordTooLong:
-      return "The password is too long.";
-    case NERR_PasswordNotComplexEnough:
-      return "The password does not meet the complexity policy.";
-    case NERR_PasswordFilterError:
-      return "The password does not meet the requirements of the password filter DLLs.";
-#endif
-
-    }
-  msg = strerror (error_number);
-  if (msg == NULL)
-    msg = "unknown";
-
-  return msg;
-#endif //DBUS_WINCE
-}
-
-
-
-
-
-
-
-
-
-/******************************************************************************
-Original CVS version of dbus-sysdeps.c
-******************************************************************************/
-/* -*- mode: C; c-file-style: "gnu" -*- */
-/* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
- * 
- * Copyright (C) 2002, 2003  Red Hat, Inc.
- * Copyright (C) 2003 CodeFactory AB
- * Copyright (C) 2005 Novell, Inc.
- *
- * 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
- * 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
- *
- */
-
-
-/**
- * @addtogroup DBusInternalsUtils
- * @{
- */
-
-int _dbus_mkdir (const char *path,
-                 mode_t mode)
-{
-  return _mkdir(path);
-}
-
-/**
- * Exit the process, returning the given value.
- *
- * @param code the exit code
- */
-void
-_dbus_exit (int code)
-{
-  _exit (code);
-}
-
-/**
- * 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, NULL for loopback
- * @param port the prot to connect to
- * @param error return location for error code
- * @returns connection file descriptor or -1 on error
- */
-int
-_dbus_connect_tcp_socket (const char     *host,
-                          dbus_uint32_t   port,
-                          DBusError      *error)
-{
-#ifdef ENABLE_DBUSSOCKET
-  DBusSocket s;
-  int handle;
-  struct sockaddr_in addr;
-  struct hostent *he;
-  struct in_addr *haddr;
-  struct in_addr ina;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-
-  _dbus_win_startup_winsock ();
-
-  s.fd = socket (AF_INET, SOCK_STREAM, 0);
-
-  if (DBUS_SOCKET_IS_INVALID (s.fd))
-    {
-      DBUS_SOCKET_SET_ERRNO ();
       dbus_set_error (error,
-                      _dbus_error_from_errno (errno),
-                      "Failed to create socket: %s",
-                      _dbus_strerror (errno));
-
+                      DBUS_ERROR_INVALID_ARGS,
+                      "Unknown address family %s", family);
       return -1;
     }
+  hints.ai_protocol = IPPROTO_TCP;
+  hints.ai_socktype = SOCK_STREAM;
+#ifdef AI_ADDRCONFIG
+  hints.ai_flags = AI_ADDRCONFIG;
+#else
+  hints.ai_flags = 0;
+#endif
 
-  if (host == NULL)
-    {
-      host = "localhost";
-      ina.s_addr = htonl (INADDR_LOOPBACK);
-      haddr = &ina;
-    }
-
-  he = gethostbyname (host);
-  if (he == NULL)
+  if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
     {
-      DBUS_SOCKET_SET_ERRNO ();
       dbus_set_error (error,
-                      _dbus_error_from_errno (errno),
-                      "Failed to lookup hostname: %s",
-                      host);
-      DBUS_CLOSE_SOCKET (s.fd);
+                      _dbus_error_from_errno (res),
+                      "Failed to lookup host/port: \"%s:%s\": %s (%d)",
+                      host, port, _dbus_strerror(res), res);
       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 (DBUS_SOCKET_API_RETURNS_ERROR
-      (connect (s.fd, (struct sockaddr*) &addr, sizeof (addr)) < 0))
+  tmp = ai;
+  while (tmp)
     {
-      DBUS_SOCKET_SET_ERRNO ();
-      dbus_set_error (error,
-                      _dbus_error_from_errno (errno),
-                      "Failed to connect to socket %s:%d %s",
-                      host, port, _dbus_strerror (errno));
-
-      DBUS_CLOSE_SOCKET (s.fd);
-      s.fd = -1;
-
-      return -1;
-    }
-
-  handle = _dbus_socket_to_handle (&s);
-
-  if (!_dbus_set_fd_nonblocking (handle, error))
-    {
-      _dbus_close_socket (handle, NULL);
-      handle = -1;
-
-      return -1;
-    }
-
-  return handle;
-#else
-  int fd;
-  struct sockaddr_in addr;
-  struct hostent *he;
-  struct in_addr *haddr;
-  struct in_addr ina;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-
-  _dbus_win_startup_winsock ();
-
-  fd = socket (AF_INET, SOCK_STREAM, 0);
-
-  if (DBUS_SOCKET_IS_INVALID (fd))
-    {
-      DBUS_SOCKET_SET_ERRNO ();
-      dbus_set_error (error,
-                      _dbus_error_from_errno (errno),
-                      "Failed to create socket: %s",
-                      _dbus_strerror (errno));
+      if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) == INVALID_SOCKET)
+        {
+          DBUS_SOCKET_SET_ERRNO ();
+          dbus_set_error (error,
+                          _dbus_error_from_errno (errno),
+                          "Failed to open socket: %s",
+                          _dbus_strerror_from_errno ());
+          freeaddrinfo(ai);
+          return -1;
+        }
+      _DBUS_ASSERT_ERROR_IS_CLEAR(error);
 
-      return -1;
-    }
+      if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
+        {
+          DBUS_SOCKET_SET_ERRNO ();
+          closesocket(fd);
+          fd = -1;
+          tmp = tmp->ai_next;
+          continue;
+        }
 
-  if (host == NULL)
-    {
-      host = "localhost";
-      ina.s_addr = htonl (INADDR_LOOPBACK);
-      haddr = &ina;
+      break;
     }
+  freeaddrinfo(ai);
 
-  he = gethostbyname (host);
-  if (he == NULL)
+  if (fd == -1)
     {
-      DBUS_SOCKET_SET_ERRNO ();
       dbus_set_error (error,
                       _dbus_error_from_errno (errno),
-                      "Failed to lookup hostname: %s",
-                      host);
-      DBUS_CLOSE_SOCKET (fd);
+                      "Failed to connect to socket \"%s:%s\" %s",
+                      host, port, _dbus_strerror_from_errno ());
       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 (DBUS_SOCKET_API_RETURNS_ERROR
-      (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0))
+  if (noncefile != NULL)
     {
-      DBUS_SOCKET_SET_ERRNO ();
-      dbus_set_error (error,
-                      _dbus_error_from_errno (errno),
-                      "Failed to connect to socket %s:%d %s",
-                      host, port, _dbus_strerror (errno));
+      DBusString noncefileStr;
+      dbus_bool_t ret;
+      if (!_dbus_string_init (&noncefileStr) ||
+          !_dbus_string_append(&noncefileStr, noncefile))
+        {
+          closesocket (fd);
+          dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+          return -1;
+        }
 
-      DBUS_CLOSE_SOCKET (fd);
-      fd = -1;
+      ret = _dbus_send_nonce (fd, &noncefileStr, error);
 
-      return -1;
+      _dbus_string_free (&noncefileStr);
+
+      if (!ret)
+        {
+          closesocket (fd);
+          return -1;
+        }
     }
 
+  _dbus_fd_set_close_on_exec (fd);
+
   if (!_dbus_set_fd_nonblocking (fd, error))
     {
-      _dbus_close_socket (fd, NULL);
-      fd = -1;
-
+      closesocket (fd);
       return -1;
     }
 
   return fd;
-#endif
 }
 
-void
-_dbus_daemon_init(const char *host, dbus_uint32_t port);
 /**
- * Creates a socket and binds it to the given port,
- * then listens on the socket. The socket is
- * set to be nonblocking. 
- * In case of port=0 a random free port is used and 
- * returned in the port parameter. 
+ * Creates a socket and binds it to the given path, then listens on
+ * the socket. The socket is set to be nonblocking.  In case of port=0
+ * a random free port is used and returned in the port parameter.
+ * If inaddr_any is specified, the hostname is ignored.
  *
- * @param host the interface to listen on, NULL for loopback, empty for any
+ * @param host the host name to listen on
  * @param port the port to listen on, if zero a free port will be used 
+ * @param family the address family to listen on, NULL for all
+ * @param retport string to return the actual port listened on
+ * @param fds_p location to store returned file descriptors
  * @param error return location for errors
- * @returns the listening file descriptor or -1 on error
+ * @returns the number of listening file descriptors or -1 on error
  */
 
 int
 _dbus_listen_tcp_socket (const char     *host,
-                         dbus_uint32_t  *port,
-                         dbus_bool_t     inaddr_any,
+                         const char     *port,
+                         const char     *family,
+                         DBusString     *retport,
+                         int           **fds_p,
                          DBusError      *error)
 {
-#ifdef ENABLE_DBUSSOCKET
-  DBusSocket slisten;
-  int handle;
-  struct sockaddr_in addr;
-  struct hostent *he;
-  struct in_addr *haddr;
-  socklen_t len = (socklen_t) sizeof (struct sockaddr);
-  struct in_addr ina;
+  int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
+  struct addrinfo hints;
+  struct addrinfo *ai, *tmp;
 
+  // On Vista, sockaddr_gen must be a sockaddr_in6, and not a sockaddr_in6_old
+  //That's required for family == IPv6(which is the default on Vista if family is not given)
+  //So we use our own union instead of sockaddr_gen:
 
+  typedef union {
+       struct sockaddr Address;
+       struct sockaddr_in AddressIn;
+       struct sockaddr_in6 AddressIn6;
+  } mysockaddr_gen;
+
+  *fds_p = NULL;
   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
 
   _dbus_win_startup_winsock ();
 
-  slisten.fd = socket (AF_INET, SOCK_STREAM, 0);
+  _DBUS_ZERO (hints);
 
-  if (DBUS_SOCKET_IS_INVALID (slisten.fd))
-    {
-      DBUS_SOCKET_SET_ERRNO ();
-      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";
-      ina.s_addr = htonl (INADDR_LOOPBACK);
-      haddr = &ina;
-    }
-  else if (!host[0])
-    {
-      ina.s_addr = htonl (INADDR_ANY);
-      haddr = &ina;
-    }
+  if (!family)
+    hints.ai_family = AF_UNSPEC;
+  else if (!strcmp(family, "ipv4"))
+    hints.ai_family = AF_INET;
+  else if (!strcmp(family, "ipv6"))
+    hints.ai_family = AF_INET6;
   else
     {
-      he = gethostbyname (host);
-      if (he == NULL)
-        {
-          DBUS_SOCKET_SET_ERRNO ();
-          dbus_set_error (error,
-                          _dbus_error_from_errno (errno),
-                          "Failed to lookup hostname: %s",
-                          host);
-          DBUS_CLOSE_SOCKET (slisten.fd);
-          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 (slisten.fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
-    {
-      DBUS_SOCKET_SET_ERRNO ();
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to bind socket \"%s:%d\": %s",
-                      host, *port, _dbus_strerror (errno));
-      DBUS_CLOSE_SOCKET (slisten.fd);
-      return -1;
-    }
-
-  if (DBUS_SOCKET_API_RETURNS_ERROR (listen (slisten.fd, 30 /* backlog */)))
-    {
-      DBUS_SOCKET_SET_ERRNO ();
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to listen on socket \"%s:%d\": %s",
-                      host, *port, _dbus_strerror (errno));
-      DBUS_CLOSE_SOCKET (slisten.fd);
-      return -1;
-    }
-
-  getsockname(slisten.fd, (struct sockaddr*) &addr, &len);
-  *port = (dbus_uint32_t) ntohs(addr.sin_port);
-  
-  _dbus_daemon_init(host, ntohs(addr.sin_port));
-
-  handle = _dbus_socket_to_handle (&slisten);
-
-  if (!_dbus_set_fd_nonblocking (handle, error))
-    {
-      _dbus_close_socket (handle, NULL);
+      dbus_set_error (error,
+                      DBUS_ERROR_INVALID_ARGS,
+                      "Unknown address family %s", family);
       return -1;
     }
 
-  return handle;
+  hints.ai_protocol = IPPROTO_TCP;
+  hints.ai_socktype = SOCK_STREAM;
+#ifdef AI_ADDRCONFIG
+  hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
 #else
-  int fd;
-  struct sockaddr_in addr;
-  struct hostent *he;
-  struct in_addr *haddr;
-  socklen_t len = (socklen_t) sizeof (struct sockaddr);
-  struct in_addr ina;
-
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-
-  _dbus_win_startup_winsock ();
-
-  fd = socket (AF_INET, SOCK_STREAM, 0);
+  hints.ai_flags = AI_PASSIVE;
+#endif
 
-  if (DBUS_SOCKET_IS_INVALID (fd))
+ redo_lookup_with_port:
+  if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
     {
-      DBUS_SOCKET_SET_ERRNO ();
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to create socket \"%s:%d\": %s",
-                      host, port, _dbus_strerror (errno));
+      dbus_set_error (error,
+                      _dbus_error_from_errno (res),
+                      "Failed to lookup host/port: \"%s:%s\": %s (%d)",
+                      host ? host : "*", port, _dbus_strerror(res), res);
       return -1;
     }
-  if (host == NULL)
-    {
-      host = "localhost";
-      ina.s_addr = htonl (INADDR_LOOPBACK);
-      haddr = &ina;
-    }
-  else if (!host[0])
-    {
-      ina.s_addr = htonl (INADDR_ANY);
-      haddr = &ina;
-    }
-  else
+
+  tmp = ai;
+  while (tmp)
     {
-      he = gethostbyname (host);
-      if (he == NULL)
+      int fd = -1, *newlisten_fd;
+      if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) == INVALID_SOCKET)
         {
           DBUS_SOCKET_SET_ERRNO ();
           dbus_set_error (error,
                           _dbus_error_from_errno (errno),
-                          "Failed to lookup hostname: %s",
-                          host);
-          DBUS_CLOSE_SOCKET (fd);
-          return -1;
+                         "Failed to open socket: %s",
+                         _dbus_strerror_from_errno ());
+          goto failed;
         }
+      _DBUS_ASSERT_ERROR_IS_CLEAR(error);
 
-      haddr = ((struct in_addr *) (he->h_addr_list)[0]);
+      if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
+        {
+          DBUS_SOCKET_SET_ERRNO ();
+          dbus_set_error (error, _dbus_error_from_errno (errno),
+                          "Failed to bind socket \"%s:%s\": %s",
+                          host ? host : "*", port, _dbus_strerror_from_errno ());
+          closesocket (fd);
+          goto failed;
     }
 
-  _DBUS_ZERO (addr);
-  memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
-  addr.sin_family = AF_INET;
-  addr.sin_port = htons (*port);
+      if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
+        {
+          DBUS_SOCKET_SET_ERRNO ();
+          dbus_set_error (error, _dbus_error_from_errno (errno),
+                          "Failed to listen on socket \"%s:%s\": %s",
+                          host ? host : "*", port, _dbus_strerror_from_errno ());
+          closesocket (fd);
+          goto failed;
+        }
 
-  if (bind (fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
-    {
-      DBUS_SOCKET_SET_ERRNO ();
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to bind socket \"%s:%d\": %s",
-                      host, *port, _dbus_strerror (errno));
-      DBUS_CLOSE_SOCKET (fd);
-      return -1;
+      newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
+      if (!newlisten_fd)
+        {
+          closesocket (fd);
+          dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
+                          "Failed to allocate file handle array");
+          goto failed;
+        }
+      listen_fd = newlisten_fd;
+      listen_fd[nlisten_fd] = fd;
+      nlisten_fd++;
+
+      if (!_dbus_string_get_length(retport))
+        {
+          /* If the user didn't specify a port, or used 0, then
+             the kernel chooses a port. After the first address
+             is bound to, we need to force all remaining addresses
+             to use the same port */
+          if (!port || !strcmp(port, "0"))
+            {
+              mysockaddr_gen addr;
+              socklen_t addrlen = sizeof(addr);
+              char portbuf[10];
+
+              if (getsockname(fd, &addr.Address, &addrlen) == SOCKET_ERROR)
+                {
+                  DBUS_SOCKET_SET_ERRNO ();
+                  dbus_set_error (error, _dbus_error_from_errno (errno),
+                                  "Failed to resolve port \"%s:%s\": %s",
+                                  host ? host : "*", port, _dbus_strerror_from_errno());
+                  goto failed;
+                }
+              snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
+              if (!_dbus_string_append(retport, portbuf))
+                {
+                  dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+                  goto failed;
+                }
+
+              /* Release current address list & redo lookup */
+              port = _dbus_string_get_const_data(retport);
+              freeaddrinfo(ai);
+              goto redo_lookup_with_port;
+            }
+          else
+            {
+              if (!_dbus_string_append(retport, port))
+                {
+                    dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+                    goto failed;
+                }
+            }
+        }
+  
+      tmp = tmp->ai_next;
     }
+  freeaddrinfo(ai);
+  ai = NULL;
 
-  if (DBUS_SOCKET_API_RETURNS_ERROR (listen (fd, 30 /* backlog */)))
+  if (!nlisten_fd)
     {
-      DBUS_SOCKET_SET_ERRNO ();
+      _dbus_win_set_errno (WSAEADDRINUSE);
       dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to listen on socket \"%s:%d\": %s",
-                      host, *port, _dbus_strerror (errno));
-      DBUS_CLOSE_SOCKET (fd);
+                      "Failed to bind socket \"%s:%s\": %s",
+                      host ? host : "*", port, _dbus_strerror_from_errno ());
       return -1;
     }
 
-  getsockname(fd, (struct sockaddr*) &addr, &len);
-  *port = (dbus_uint32_t) ntohs(addr.sin_port);
-  
-  _dbus_daemon_init(host, ntohs(addr.sin_port));
+  sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
 
-  if (!_dbus_set_fd_nonblocking (fd, error))
+  for (i = 0 ; i < nlisten_fd ; i++)
     {
-      _dbus_close_socket (fd, NULL);
-      return -1;
+      _dbus_fd_set_close_on_exec (listen_fd[i]);
+      if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
+        {
+          goto failed;
+        }
     }
 
-  return fd;
-#endif
+  *fds_p = listen_fd;
+
+  return nlisten_fd;
+
+ failed:
+  if (ai)
+    freeaddrinfo(ai);
+  for (i = 0 ; i < nlisten_fd ; i++)
+    closesocket (listen_fd[i]);
+  dbus_free(listen_fd);
+  return -1;
 }
 
 
@@ -3863,67 +1815,23 @@ _dbus_listen_tcp_socket (const char     *host,
  * @returns the connection fd of the client, or -1 on error
  */
 int
-_dbus_accept  (int listen_handle)
+_dbus_accept  (int listen_fd)
 {
-#ifdef ENABLE_DBUSSOCKET
-  DBusSocket *slisten;
-  DBusSocket sclient;
-  struct sockaddr addr;
-  socklen_t addrlen;
-
-  _dbus_handle_to_socket(listen_handle, &slisten);
-
-  addrlen = sizeof (addr);
-
-  //FIXME:  why do we not try it again on Windows?
-#if !defined(DBUS_WIN) && !defined(DBUS_WINCE)
-retry:
-#endif
-
-  sclient.fd = accept (slisten->fd, &addr, &addrlen);
-
-  if (DBUS_SOCKET_IS_INVALID (sclient.fd))
-    {
-      DBUS_SOCKET_SET_ERRNO ();
-#if !defined(DBUS_WIN) && !defined(DBUS_WINCE)
-      if (errno == EINTR)
-        goto retry;
-#else
-      return -1;
-#endif
-    }
-
-  return _dbus_socket_to_handle (&sclient);
-#else
-  int fd;
-  int sclient;
-  struct sockaddr addr;
-  socklen_t addrlen;
-
-  fd = listen_handle;
-
-  addrlen = sizeof (addr);
-
-  //FIXME:  why do we not try it again on Windows?
-#if !defined(DBUS_WIN) && !defined(DBUS_WINCE)
-retry:
-#endif
+  int client_fd;
 
-  sclient = accept (fd, &addr, &addrlen);
+ retry:
+  client_fd = accept (listen_fd, NULL, NULL);
 
-  if (DBUS_SOCKET_IS_INVALID (sclient))
+  if (DBUS_SOCKET_IS_INVALID (client_fd))
     {
       DBUS_SOCKET_SET_ERRNO ();
-#if !defined(DBUS_WIN) && !defined(DBUS_WINCE)
       if (errno == EINTR)
         goto retry;
-#else
-      return -1;
-#endif
     }
 
-  return sclient;
-#endif
+  _dbus_verbose ("client fd %d accepted\n", client_fd);
+  
+  return client_fd;
 }
 
 
@@ -3970,7 +1878,7 @@ again:
     {
       dbus_set_error (error, _dbus_error_from_errno (errno),
                       "Failed to write credentials byte: %s",
-                     _dbus_strerror (errno));
+                     _dbus_strerror_from_errno ());
       return FALSE;
     }
   else if (bytes_written == 0)
@@ -3989,56 +1897,65 @@ again:
 }
 
 /**
- * Gets the credentials of the current process.
- *
- * @param credentials credentials to fill in.
- */
-void
-_dbus_credentials_from_current_process (DBusCredentials *credentials)
-{
-  credentials->pid = _dbus_getpid ();
-  credentials->uid = _dbus_getuid ();
-  credentials->gid = _dbus_getgid ();
-}
-
-/**
  * 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 handle 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_socket  (int              handle,
-                                     DBusCredentials *credentials,
-                                     DBusError       *error)
+                                DBusCredentials *credentials,
+                                DBusError       *error)
 {
-  int bytes_read;
+  int bytes_read = 0;
   DBusString buf;
-  _dbus_string_init(&buf);
 
-  bytes_read = _dbus_read_socket(handle, &buf, 1 );
-  if (bytes_read > 0) 
+  char *sid = NULL;
+  dbus_pid_t pid;
+  int retval = FALSE;
+
+  // could fail due too OOM
+  if (_dbus_string_init (&buf))
     {
-               _dbus_verbose("got one zero byte from server");
+      bytes_read = _dbus_read_socket (handle, &buf, 1 );
+
+      if (bytes_read > 0) 
+        _dbus_verbose ("got one zero byte from server\n");
+
+      _dbus_string_free (&buf);
     }
 
-  _dbus_string_free(&buf);
-  _dbus_credentials_from_current_process (credentials);
-  _dbus_verbose("FIXME: get faked credentials from current process");
+  pid = _dbus_get_peer_pid_from_tcp_handle (handle);
+  if (pid == 0)
+    return TRUE;
+
+  _dbus_credentials_add_pid (credentials, pid);
 
-  return TRUE;
+  if (_dbus_getsid (&sid, pid))
+    {
+      if (!_dbus_credentials_add_windows_sid (credentials, sid))
+        goto out;
+    }
+
+  retval = TRUE;
+
+out:
+  if (sid)
+    LocalFree (sid);
+
+  return retval;
 }
 
 /**
@@ -4052,101 +1969,13 @@ _dbus_read_credentials_socket  (int              handle,
 dbus_bool_t
 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
 {
-  const char *directory;
-  struct stat sb;
-
+  /* TODO */
   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-
-  return TRUE;
-}
-
-#ifdef ENABLE_DBUSUSERINFO
-dbus_bool_t
-fill_user_info (DBusUserInfo       *info,
-                dbus_uid_t          uid,
-                const DBusString   *username,
-                DBusError          *error)
-{
-  const char *username_c;
-
-  /* exactly one of username/uid provided */
-  _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
-  _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
-
-  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;
-
-  if (username != NULL)
-    username_c = _dbus_string_get_const_data (username);
-  else
-    username_c = NULL;
-
-  if (uid != DBUS_UID_UNSET)
-    {
-      if (!fill_win_user_info_from_uid (uid, info, error))
-        {
-          _dbus_verbose("%s after fill_win_user_info_from_uid\n",__FUNCTION__);
-          return FALSE;
-        }
-    }
-  else
-    {
-      wchar_t *wname = _dbus_win_utf8_to_utf16 (username_c, error);
-
-      if (!wname)
-        return FALSE;
-
-      if (!fill_win_user_info_from_name (wname, info, error))
-        {
-          dbus_free (wname);
-          return FALSE;
-        }
-      dbus_free (wname);
-    }
-
   return TRUE;
 }
-/**
- * Gets user info for the given user ID.
- *
- * @param info user info object to initialize
- * @param uid the user ID
- * @param error error return
- * @returns #TRUE on success
- */
-dbus_bool_t
-_dbus_user_info_fill_uid (DBusUserInfo *info,
-                          dbus_uid_t    uid,
-                          DBusError    *error)
-{
-  return fill_user_info (info, uid,
-                         NULL, error);
-}
 
 
 /**
- * Gets user info for the given username.
- *
- * @param info user info object to initialize
- * @param username the username
- * @param error error return
- * @returns #TRUE on success
- */
-dbus_bool_t
-_dbus_user_info_fill (DBusUserInfo     *info,
-                      const DBusString *username,
-                      DBusError        *error)
-{
-  return fill_user_info (info, DBUS_UID_UNSET,
-                         username, error);
-}
-#endif
-
-/**
  * Appends the given filename to the given directory.
  *
  * @todo it might be cute to collapse multiple '/' such as "foo//"
@@ -4168,109 +1997,28 @@ _dbus_concat_dir_and_file (DBusString       *dir,
     return TRUE;
 
   dir_ends_in_slash =
-    ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
-     '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
-
-  file_starts_with_slash =
-    ('/' == _dbus_string_get_byte (next_component, 0) ||
-     '\\' == _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));
-}
-
-/**
- * Adds the credentials of the current process to the
- * passed-in credentials object.
- *
- * @param credentials credentials to add to
- * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
- */
-
-dbus_bool_t
-_dbus_credentials_add_from_current_process (DBusCredentials *credentials)
-{
-  credentials->pid = _dbus_getpid();
-  credentials->uid = _dbus_getuid();
-  return TRUE;
-}
-
-
-/**
- * Gets a UID from a UID string.
- *
- * @param uid_str the UID in string form
- * @param uid UID to fill in
- * @returns #TRUE if successfully filled in UID
- */
-dbus_bool_t
-_dbus_parse_uid (const DBusString      *uid_str,
-                 dbus_uid_t            *uid)
-{
-  int end;
-  long val;
-  
-  if (_dbus_string_get_length (uid_str) == 0)
-    {
-      _dbus_verbose ("UID string was zero length\n");
-      return FALSE;
-    }
+    ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
+     '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
+
+  file_starts_with_slash =
+    ('/' == _dbus_string_get_byte (next_component, 0) ||
+     '\\' == _dbus_string_get_byte (next_component, 0));
 
-  val = -1;
-  end = 0;
-  if (!_dbus_string_parse_int (uid_str, 0, &val,
-                               &end))
+  if (dir_ends_in_slash && file_starts_with_slash)
     {
-      _dbus_verbose ("could not parse string as a UID\n");
-      return FALSE;
+      _dbus_string_shorten (dir, 1);
     }
-  
-  if (end != _dbus_string_get_length (uid_str))
+  else if (!(dir_ends_in_slash || file_starts_with_slash))
     {
-      _dbus_verbose ("string contained trailing stuff after UID\n");
-      return FALSE;
+      if (!_dbus_string_append_byte (dir, '\\'))
+        return FALSE;
     }
 
-  *uid = val;
-
-  return TRUE;
+  return _dbus_string_copy (next_component, 0, dir,
+                            _dbus_string_get_length (dir));
 }
 
-/**
- * Parses a desired identity provided from a client in the auth protocol.
- * On UNIX this means parsing a UID.
- *
- * @todo this is broken because it treats OOM and parse error
- * the same way. Needs a #DBusError.
- * 
- * @param credentials the credentials to add what we parse to
- * @param desired_identity the string to parse
- * @returns #TRUE if we successfully parsed something
- */
-dbus_bool_t
-_dbus_credentials_parse_and_add_desired (DBusCredentials  *credentials,
-                                         const DBusString *desired_identity)
-{
-  dbus_uid_t uid;
-
-  if (!_dbus_parse_uid (desired_identity, &uid))
-    return FALSE;
-
-  if (!_dbus_credentials_add_unix_uid (credentials, uid))
-    return FALSE;
-
-  return TRUE;
-}
+/*---------------- DBusCredentials ----------------------------------*/
 
 /**
  * Adds the credentials corresponding to the given username.
@@ -4283,8 +2031,42 @@ dbus_bool_t
 _dbus_credentials_add_from_user (DBusCredentials  *credentials,
                                      const DBusString *username)
 {
-  _dbus_verbose("_dbus_credentials_add_from_user is not implemented");
-  return FALSE;
+  return _dbus_credentials_add_windows_sid (credentials,
+                    _dbus_string_get_const_data(username));
+}
+
+/**
+ * Adds the credentials of the current process to the
+ * passed-in credentials object.
+ *
+ * @param credentials credentials to add to
+ * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
+ */
+
+dbus_bool_t
+_dbus_credentials_add_from_current_process (DBusCredentials *credentials)
+{
+  dbus_bool_t retval = FALSE;
+  char *sid = NULL;
+
+  if (!_dbus_getsid(&sid, _dbus_getpid()))
+    goto failed;
+
+  if (!_dbus_credentials_add_pid (credentials, _dbus_getpid()))
+    goto failed;
+
+  if (!_dbus_credentials_add_windows_sid (credentials,sid))
+    goto failed;
+
+  retval = TRUE;
+  goto end;
+failed:
+  retval = FALSE;
+end:
+  if (sid)
+    LocalFree(sid);
+
+  return retval;
 }
 
 /**
@@ -4297,68 +2079,28 @@ _dbus_credentials_add_from_user (DBusCredentials  *credentials,
  * 
  * @param str the string to append to
  * @returns #FALSE on no memory
+ * @todo to which class belongs this 
  */
 dbus_bool_t
 _dbus_append_user_from_current_process (DBusString *str)
 {
-  return _dbus_string_append_uint (str,
-                                   _dbus_getuid ());
-}
+  dbus_bool_t retval = FALSE;
+  char *sid = NULL;
 
-/**
- * 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)
-{
-    _dbus_string_append (homedir, "/");
-    return TRUE;
-}
+  if (!_dbus_getsid(&sid, _dbus_getpid()))
+    return FALSE;
 
-/**
- * Gets homedir of user owning current process.  The returned string
- * is valid until dbus_shutdown() is called.
- *
- * @param homedir place to store pointer to homedir
- * @returns #FALSE if no memory
- */
-dbus_bool_t
-_dbus_homedir_from_current_process (const DBusString  **homedir)
-{
-  char *s = getenv("HOMEPATH");
-  DBusString *dir=0;
-  _dbus_string_init(dir);
-  _dbus_string_append (dir, s);
-  *homedir = dir;
-  return TRUE;
-}
+  retval = _dbus_string_append (str,sid);
 
-/**
- * Append to the string the identity we would like to have when we authenticate,
- * on UNIX this is the current process UID and on Windows something else.
- * No escaping is required, that is done in dbus-auth.c.
- * 
- * @param str the string to append to
- * @returns #FALSE on no memory
- */
-dbus_bool_t
-_dbus_append_desired_identity (DBusString *str)
-{
-    /* FIXME: */
-  return _dbus_string_append_uint (str,
-                                   _dbus_getuid ());
+  LocalFree(sid);
+  return retval;
 }
 
 /**
  * Gets our process ID
  * @returns process ID
  */
-unsigned long
+dbus_pid_t
 _dbus_getpid (void)
 {
   return GetCurrentProcessId ();
@@ -4387,330 +2129,59 @@ _dbus_sleep_milliseconds (int milliseconds)
 
 
 /**
- * Get current time, as in gettimeofday().
+ * Get current time, as in gettimeofday(). Never uses the monotonic
+ * clock.
  *
  * @param tv_sec return location for number of seconds
  * @param tv_usec return location for number of microseconds
  */
 void
-_dbus_get_current_time (long *tv_sec,
-                        long *tv_usec)
+_dbus_get_real_time (long *tv_sec,
+                     long *tv_usec)
 {
   FILETIME ft;
-  dbus_uint64_t *time64 = (dbus_uint64_t *) &ft;
+  dbus_uint64_t time64;
 
   GetSystemTimeAsFileTime (&ft);
 
+  memcpy (&time64, &ft, sizeof (time64));
+
   /* Convert from 100s of nanoseconds since 1601-01-01
   * to Unix epoch. Yes, this is Y2038 unsafe.
   */
-  *time64 -= DBUS_INT64_CONSTANT (116444736000000000);
-  *time64 /= 10;
+  time64 -= DBUS_INT64_CONSTANT (116444736000000000);
+  time64 /= 10;
 
   if (tv_sec)
-    *tv_sec = *time64 / 1000000;
+    *tv_sec = time64 / 1000000;
 
   if (tv_usec)
-    *tv_usec = *time64 % 1000000;
-}
-
-
-/**
- * signal (SIGPIPE, SIG_IGN);
- */
-void
-_dbus_disable_sigpipe (void)
-{
-    _dbus_verbose("FIXME: implement _dbus_disable_sigpipe (void)\n");
+    *tv_usec = time64 % 1000000;
 }
 
-
 /**
- * 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.
+ * Get current time, as in gettimeofday(). Use the monotonic clock if
+ * available, to avoid problems when the system time changes.
  *
- * @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
+ * @param tv_sec return location for number of seconds
+ * @param tv_usec return location for number of microseconds
  */
-dbus_bool_t
-_dbus_file_get_contents (DBusString       *str,
-                         const DBusString *filename,
-                         DBusError        *error)
+void
+_dbus_get_monotonic_time (long *tv_sec,
+                          long *tv_usec)
 {
-  DBusFile file;
-  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 and Win32 */
-  if (!_dbus_file_open (&file, filename_c, O_RDONLY | O_BINARY, -1))
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to open \"%s\": %s",
-                      filename_c,
-                      _dbus_strerror (errno));
-      return FALSE;
-    }
-
-  if (!_dbus_fstat (&file, &sb))
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to stat \"%s\": %s",
-                      filename_c,
-                      _dbus_strerror (errno));
-
-      _dbus_verbose ("fstat() failed: %s",
-                     _dbus_strerror (errno));
-
-      _dbus_file_close (&file, NULL);
-
-      return FALSE;
-    }
-
-  if (sb.st_size > _DBUS_ONE_MEGABYTE)
-    {
-      dbus_set_error (error, DBUS_ERROR_FAILED,
-                      "File size %lu of \"%s\" is too large.",
-                      (unsigned long) sb.st_size, filename_c);
-      _dbus_file_close (&file, NULL);
-      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_file_read (&file, str,
-                                        sb.st_size - total);
-          if (bytes_read <= 0)
-            {
-              dbus_set_error (error, _dbus_error_from_errno (errno),
-                              "Error reading \"%s\": %s",
-                              filename_c,
-                              _dbus_strerror (errno));
-
-              _dbus_verbose ("read() failed: %s",
-                             _dbus_strerror (errno));
-
-              _dbus_file_close (&file, NULL);
-              _dbus_string_set_length (str, orig_len);
-              return FALSE;
-            }
-          else
-            total += bytes_read;
-        }
-
-      _dbus_file_close (&file, NULL);
-      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,
-                      "\"%s\" is not a regular file",
-                      filename_c);
-      _dbus_file_close (&file, NULL);
-      return FALSE;
-    }
-  else
-    {
-      _dbus_file_close (&file, NULL);
-      return TRUE;
-    }
+  /* no implementation yet, fall back to wall-clock time */
+  _dbus_get_real_time (tv_sec, tv_usec);
 }
 
 /**
- * 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)
-{
-  DBusFile file;
-  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);
-
-  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);
-      _dbus_string_free (&tmp_filename);
-      return FALSE;
-    }
-
-  if (!_dbus_string_append (&tmp_filename, "."))
-    {
-      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
-      _dbus_string_free (&tmp_filename);
-      return FALSE;
-    }
-
-#define N_TMP_FILENAME_RANDOM_BYTES 8
-  if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
-    {
-      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
-      _dbus_string_free (&tmp_filename);
-      return FALSE;
-    }
-
-  filename_c = _dbus_string_get_const_data (filename);
-  tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
-
-  if (!_dbus_file_open (&file, tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
-                        0600))
-    {
-      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_file_write (&file, 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 (!_dbus_file_close (&file, NULL))
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Could not close file %s: %s",
-                      tmp_filename_c, _dbus_strerror (errno));
-
-      goto out;
-    }
-
-
-  if ((unlink (filename_c) == -1 && errno != ENOENT) ||
-       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 (_dbus_is_valid_file(&file))
-    _dbus_file_close (&file, NULL);
-
-  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
+ * signal (SIGPIPE, SIG_IGN);
  */
-dbus_bool_t
-_dbus_create_file_exclusively (const DBusString *filename,
-                               DBusError        *error)
+void
+_dbus_disable_sigpipe (void)
 {
-  DBusFile file;
-  const char *filename_c;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-
-  filename_c = _dbus_string_get_const_data (filename);
-
-  if (!_dbus_file_open (&file, filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
-                        0600))
-    {
-      dbus_set_error (error,
-                      DBUS_ERROR_FAILED,
-                      "Could not create file %s: %s\n",
-                      filename_c,
-                      _dbus_strerror (errno));
-      return FALSE;
-    }
-
-  if (!_dbus_file_close (&file, NULL))
-    {
-      dbus_set_error (error,
-                      DBUS_ERROR_FAILED,
-                      "Could not close file %s: %s\n",
-                      filename_c,
-                      _dbus_strerror (errno));
-      return FALSE;
-    }
-
-  return TRUE;
 }
 
-
 /**
  * Creates a directory; succeeds if the directory
  * is created or already existed.
@@ -4729,14 +2200,14 @@ _dbus_create_directory (const DBusString *filename,
 
   filename_c = _dbus_string_get_const_data (filename);
 
-  if (_dbus_mkdir (filename_c, 0700) < 0)
+  if (!CreateDirectoryA (filename_c, NULL))
     {
-      if (errno == EEXIST)
+      if (GetLastError () == ERROR_ALREADY_EXISTS)
         return TRUE;
 
       dbus_set_error (error, DBUS_ERROR_FAILED,
                       "Failed to create directory %s: %s\n",
-                      filename_c, _dbus_strerror (errno));
+                      filename_c, _dbus_strerror_from_errno ());
       return FALSE;
     }
   else
@@ -4744,41 +2215,21 @@ _dbus_create_directory (const DBusString *filename,
 }
 
 
-static void
-pseudorandom_generate_random_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);
-
-  _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;
-
-      buffer[i] = b;
-
-      ++i;
-    }
-}
-
-static dbus_bool_t
-pseudorandom_generate_random_bytes (DBusString *str,
-                                    int         n_bytes)
+/**
+ * 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
+ */
+dbus_bool_t
+_dbus_generate_random_bytes (DBusString *str,
+                             int         n_bytes)
 {
   int old_len;
   char *p;
+  HCRYPTPROV hprov;
 
   old_len = _dbus_string_get_length (str);
 
@@ -4787,7 +2238,16 @@ pseudorandom_generate_random_bytes (DBusString *str,
 
   p = _dbus_string_get_data_len (str, old_len, n_bytes);
 
-  pseudorandom_generate_random_bytes_buffer (p, n_bytes);
+  if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
+    return FALSE;
+
+  if (!CryptGenRandom (hprov, n_bytes, p))
+    {
+      CryptReleaseContext (hprov, 0);
+      return FALSE;
+    }
+
+  CryptReleaseContext (hprov, 0);
 
   return TRUE;
 }
@@ -4802,17 +2262,27 @@ const char*
 _dbus_get_tmpdir(void)
 {
   static const char* tmpdir = NULL;
+  static char buf[1000];
 
   if (tmpdir == NULL)
     {
-      if (tmpdir == NULL)
-        tmpdir = getenv("TMP");
-      if (tmpdir == NULL)
-        tmpdir = getenv("TEMP");
-      if (tmpdir == NULL)
-        tmpdir = getenv("TMPDIR");
-      if (tmpdir == NULL)
-          tmpdir = "C:\\Temp";
+      char *last_slash;
+
+      if (!GetTempPathA (sizeof (buf), buf))
+        {
+          _dbus_warn ("GetTempPath failed\n");
+          _dbus_abort ();
+        }
+
+      /* Drop terminating backslash or slash */
+      last_slash = _mbsrchr (buf, '\\');
+      if (last_slash > buf && last_slash[1] == '\0')
+        last_slash[0] = '\0';
+      last_slash = _mbsrchr (buf, '/');
+      if (last_slash > buf && last_slash[1] == '\0')
+        last_slash[0] = '\0';
+
+      tmpdir = buf;
     }
 
   _dbus_assert(tmpdir != NULL);
@@ -4839,35 +2309,64 @@ _dbus_delete_file (const DBusString *filename,
 
   filename_c = _dbus_string_get_const_data (filename);
 
-  if (unlink (filename_c) < 0)
+  if (DeleteFileA (filename_c) == 0)
     {
       dbus_set_error (error, DBUS_ERROR_FAILED,
                       "Failed to delete file %s: %s\n",
-                      filename_c, _dbus_strerror (errno));
+                      filename_c, _dbus_strerror_from_errno ());
       return FALSE;
     }
   else
     return TRUE;
 }
 
-/**
- * Generates the given number of random bytes,
- * using the best mechanism we can come up with.
+/*
+ * replaces the term DBUS_PREFIX in configure_time_path by the
+ * current dbus installation directory. On unix this function is a noop
  *
- * @param str the string
- * @param n_bytes the number of random bytes to append to string
- * @returns #TRUE on success, #FALSE if no memory
+ * @param configure_time_path
+ * @return real path
  */
-dbus_bool_t
-_dbus_generate_random_bytes (DBusString *str,
-                             int         n_bytes)
+const char *
+_dbus_replace_install_prefix (const char *configure_time_path)
 {
-  return pseudorandom_generate_random_bytes (str, n_bytes);
+#ifndef DBUS_PREFIX
+  return configure_time_path;
+#else
+  static char retval[1000];
+  static char runtime_prefix[1000];
+  int len = 1000;
+  int i;
+
+  if (!configure_time_path)
+    return NULL;
+
+  if ((!_dbus_get_install_root(runtime_prefix, len) ||
+       strncmp (configure_time_path, DBUS_PREFIX "/",
+                strlen (DBUS_PREFIX) + 1))) {
+     strcat (retval, configure_time_path);
+     return retval;
+  }
+
+  strcpy (retval, runtime_prefix);
+  strcat (retval, configure_time_path + strlen (DBUS_PREFIX) + 1);
+
+  /* Somehow, in some situations, backslashes get collapsed in the string.
+   * Since windows C library accepts both forward and backslashes as
+   * path separators, convert all backslashes to forward slashes.
+   */
+
+  for(i = 0; retval[i] != '\0'; i++) {
+    if(retval[i] == '\\')
+      retval[i] = '/';
+  }
+  return retval;
+#endif
 }
 
-#if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
+#if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_ENABLE_EMBEDDED_TESTS)
 
-#ifdef _MSC_VER
+#if defined(_MSC_VER) || defined(DBUS_WINCE)
 # ifdef BACKTRACES
 #  undef BACKTRACES
 # endif
@@ -4894,7 +2393,7 @@ _dbus_generate_random_bytes (DBusString *str,
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
  */
 
 #include <winver.h>
@@ -4928,6 +2427,16 @@ static BOOL (WINAPI *pStackWalk)(
   PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
   PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
 );
+#ifdef _WIN64
+static DWORD64 (WINAPI *pSymGetModuleBase)(
+  HANDLE hProcess,
+  DWORD64 dwAddr
+);
+static PVOID  (WINAPI *pSymFunctionTableAccess)(
+  HANDLE hProcess,
+  DWORD64 AddrBase
+);
+#else
 static DWORD (WINAPI *pSymGetModuleBase)(
   HANDLE hProcess,
   DWORD dwAddr
@@ -4936,6 +2445,7 @@ static PVOID  (WINAPI *pSymFunctionTableAccess)(
   HANDLE hProcess,
   DWORD AddrBase
 );
+#endif
 static BOOL  (WINAPI *pSymInitialize)(
   HANDLE hProcess,
   PSTR UserSearchPath,
@@ -4990,6 +2500,16 @@ PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
+#ifdef _WIN64
+    pSymGetModuleBase=(DWORD64  (WINAPI *)(
+  HANDLE hProcess,
+  DWORD64 dwAddr
+))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
+    pSymFunctionTableAccess=(PVOID  (WINAPI *)(
+  HANDLE hProcess,
+  DWORD64 AddrBase
+))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
+#else
     pSymGetModuleBase=(DWORD  (WINAPI *)(
   HANDLE hProcess,
   DWORD dwAddr
@@ -4998,6 +2518,7 @@ PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
   HANDLE hProcess,
   DWORD AddrBase
 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
+#endif
     pSymInitialize = (BOOL  (WINAPI *)(
   HANDLE hProcess,
   PSTR UserSearchPath,
@@ -5043,7 +2564,7 @@ static void dump_backtrace_for_thread(HANDLE hThread)
 
     DPRINTF("Backtrace:\n");
 
-    memset(&context, 0, sizeof(context));
+    _DBUS_ZERO(context);
     context.ContextFlags = CONTEXT_FULL;
 
     SuspendThread(hThread);
@@ -5055,7 +2576,7 @@ static void dump_backtrace_for_thread(HANDLE hThread)
         return;
     }
 
-    memset(&sf, 0, sizeof(sf));
+    _DBUS_ZERO(sf);
 
 #ifdef __i386__
     sf.AddrFrame.Offset = context.Ebp;
@@ -5063,6 +2584,24 @@ static void dump_backtrace_for_thread(HANDLE hThread)
     sf.AddrPC.Offset = context.Eip;
     sf.AddrPC.Mode = AddrModeFlat;
     dwImageType = IMAGE_FILE_MACHINE_I386;
+#elif _M_X64
+  dwImageType                = IMAGE_FILE_MACHINE_AMD64;
+  sf.AddrPC.Offset    = context.Rip;
+  sf.AddrPC.Mode      = AddrModeFlat;
+  sf.AddrFrame.Offset = context.Rsp;
+  sf.AddrFrame.Mode   = AddrModeFlat;
+  sf.AddrStack.Offset = context.Rsp;
+  sf.AddrStack.Mode   = AddrModeFlat;
+#elif _M_IA64
+  dwImageType                 = IMAGE_FILE_MACHINE_IA64;
+  sf.AddrPC.Offset    = context.StIIP;
+  sf.AddrPC.Mode      = AddrModeFlat;
+  sf.AddrFrame.Offset = context.IntSp;
+  sf.AddrFrame.Mode   = AddrModeFlat;
+  sf.AddrBStore.Offset= context.RsBSP;
+  sf.AddrBStore.Mode  = AddrModeFlat;
+  sf.AddrStack.Offset = context.IntSp;
+  sf.AddrStack.Mode   = AddrModeFlat;
 #else
 # error You need to fill in the STACKFRAME structure for your architecture
 #endif
@@ -5121,7 +2660,10 @@ static void dump_backtrace()
     CloseHandle(hThread);
     CloseHandle(hCurrentThread);
 }
+#endif
+#endif /* asserts or tests enabled */
 
+#ifdef BACKTRACES
 void _dbus_print_backtrace(void)
 {
   init_backtrace();
@@ -5222,7 +2764,7 @@ HANDLE _dbus_global_lock (const char *mutexname)
   HANDLE mutex;
   DWORD gotMutex;
 
-  mutex = CreateMutex( NULL, FALSE, mutexname );
+  mutex = CreateMutexA( NULL, FALSE, mutexname );
   if( !mutex )
     {
       return FALSE;
@@ -5253,7 +2795,7 @@ void _dbus_global_unlock (HANDLE mutex)
 // for proper cleanup in dbus-daemon
 static HANDLE hDBusDaemonMutex = NULL;
 static HANDLE hDBusSharedMem = NULL;
-// sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
+// sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
 // sync _dbus_get_autolaunch_address
 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
@@ -5262,59 +2804,194 @@ static const char *cDBusDaemonMutex = "DBusDaemonMutex";
 // named shm for dbus adress info (per user)
 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
 
-void
-_dbus_daemon_init(const char *host, dbus_uint32_t port)
+static dbus_bool_t
+_dbus_get_install_root_as_hash(DBusString *out)
+{
+    DBusString install_path;
+
+    char path[MAX_PATH*2];
+    int path_size = sizeof(path);
+
+    if (!_dbus_get_install_root(path,path_size))
+        return FALSE;
+
+    _dbus_string_init(&install_path);
+    _dbus_string_append(&install_path,path);
+
+    _dbus_string_init(out);
+    _dbus_string_tolower_ascii(&install_path,0,_dbus_string_get_length(&install_path));
+
+    if (!_dbus_sha_compute (&install_path, out))
+        return FALSE;
+
+    return TRUE;
+}
+
+static dbus_bool_t
+_dbus_get_address_string (DBusString *out, const char *basestring, const char *scope)
+{
+  _dbus_string_init(out);
+  _dbus_string_append(out,basestring);
+
+  if (!scope)
+    {
+      return TRUE;
+    }
+  else if (strcmp(scope,"*install-path") == 0
+        // for 1.3 compatibility
+        || strcmp(scope,"install-path") == 0)
+    {
+      DBusString temp;
+      if (!_dbus_get_install_root_as_hash(&temp))
+        {
+          _dbus_string_free(out);
+           return FALSE;
+        }
+      _dbus_string_append(out,"-");
+      _dbus_string_append(out,_dbus_string_get_const_data(&temp));
+      _dbus_string_free(&temp);
+    }
+  else if (strcmp(scope,"*user") == 0)
+    {
+      _dbus_string_append(out,"-");
+      if (!_dbus_append_user_from_current_process(out))
+        {
+           _dbus_string_free(out);
+           return FALSE;
+        }
+    }
+  else if (strlen(scope) > 0)
+    {
+      _dbus_string_append(out,"-");
+      _dbus_string_append(out,scope);
+      return TRUE;
+    }
+  return TRUE;
+}
+
+static dbus_bool_t
+_dbus_get_shm_name (DBusString *out,const char *scope)
+{
+  return _dbus_get_address_string (out,cDBusDaemonAddressInfo,scope);
+}
+
+static dbus_bool_t
+_dbus_get_mutex_name (DBusString *out,const char *scope)
+{
+  return _dbus_get_address_string (out,cDBusDaemonMutex,scope);
+}
+
+dbus_bool_t
+_dbus_daemon_is_session_bus_address_published (const char *scope)
 {
   HANDLE lock;
-  const char *adr = NULL;
-  char szUserName[64];
-  DWORD dwUserNameSize = sizeof(szUserName);
-  char szDBusDaemonMutex[128];
-  char szDBusDaemonAddressInfo[128];
-  char szAddress[128];
+  DBusString mutex_name;
+
+  if (!_dbus_get_mutex_name(&mutex_name,scope))
+    {
+      _dbus_string_free( &mutex_name );
+      return FALSE;
+    }
+
+  if (hDBusDaemonMutex)
+      return TRUE;
 
-  _dbus_assert(host);
-  _dbus_assert(port);
+  // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
+  lock = _dbus_global_lock( cUniqueDBusInitMutex );
+
+  // we use CreateMutex instead of OpenMutex because of possible race conditions,
+  // see http://msdn.microsoft.com/en-us/library/ms684315%28VS.85%29.aspx
+  hDBusDaemonMutex = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
+
+  /* The client uses mutex ownership to detect a running server, so the server should do so too.
+     Fortunally the client deletes the mutex in the lock protected area, so checking presence 
+     will work too.  */
+
+  _dbus_global_unlock( lock );
+
+  _dbus_string_free( &mutex_name );
 
-  _snprintf(szAddress, sizeof(szAddress) - 1, "tcp:host=%s,port=%d", host, port);
+  if (hDBusDaemonMutex  == NULL)
+      return FALSE;
+  if (GetLastError() == ERROR_ALREADY_EXISTS)
+    {
+      CloseHandle(hDBusDaemonMutex);
+      hDBusDaemonMutex = NULL;
+      return TRUE;
+    }
+  // mutex wasn't created before, so return false.
+  // We leave the mutex name allocated for later reusage
+  // in _dbus_daemon_publish_session_bus_address.
+  return FALSE;
+}
 
-  _dbus_assert( GetUserName(szUserName, &dwUserNameSize) != 0);
-  _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
-            cDBusDaemonMutex, szUserName);
-  _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
-            cDBusDaemonAddressInfo, szUserName);
+dbus_bool_t
+_dbus_daemon_publish_session_bus_address (const char* address, const char *scope)
+{
+  HANDLE lock;
+  char *shared_addr = NULL;
+  DBusString shm_name;
+  DBusString mutex_name;
 
-  // before _dbus_global_lock to keep correct lock/release order
-  hDBusDaemonMutex = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
+  _dbus_assert (address);
 
-  _dbus_assert(WaitForSingleObject( hDBusDaemonMutex, 1000 ) == WAIT_OBJECT_0);
+  if (!_dbus_get_mutex_name(&mutex_name,scope))
+    {
+      _dbus_string_free( &mutex_name );
+      return FALSE;
+    }
 
-  // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
+  // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
   lock = _dbus_global_lock( cUniqueDBusInitMutex );
 
+  if (!hDBusDaemonMutex)
+    {
+      hDBusDaemonMutex = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
+    }
+  _dbus_string_free( &mutex_name );
+
+  // acquire the mutex
+  if (WaitForSingleObject( hDBusDaemonMutex, 10 ) != WAIT_OBJECT_0)
+    {
+      _dbus_global_unlock( lock );
+      CloseHandle( hDBusDaemonMutex );
+      return FALSE;
+    }
+
+  if (!_dbus_get_shm_name(&shm_name,scope))
+    {
+      _dbus_string_free( &shm_name );
+      _dbus_global_unlock( lock );
+      return FALSE;
+    }
+
   // create shm
-  hDBusSharedMem = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
-                                      0, strlen( szAddress ) + 1, szDBusDaemonAddressInfo );
+  hDBusSharedMem = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
+                                       0, strlen( address ) + 1, _dbus_string_get_const_data(&shm_name) );
   _dbus_assert( hDBusSharedMem );
 
-  adr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
+  shared_addr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
 
-  _dbus_assert( adr );
+  _dbus_assert (shared_addr);
 
-  strcpy(adr, szAddress);
+  strcpy( shared_addr, address);
 
   // cleanup
-  UnmapViewOfFile( adr );
+  UnmapViewOfFile( shared_addr );
 
   _dbus_global_unlock( lock );
+  _dbus_verbose( "published session bus address at %s\n",_dbus_string_get_const_data (&shm_name) );
+
+  _dbus_string_free( &shm_name );
+  return TRUE;
 }
 
 void
-_dbus_daemon_release()
+_dbus_daemon_unpublish_session_bus_address (void)
 {
   HANDLE lock;
 
-  // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
+  // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
   lock = _dbus_global_lock( cUniqueDBusInitMutex );
 
   CloseHandle( hDBusSharedMem );
@@ -5331,41 +3008,36 @@ _dbus_daemon_release()
 }
 
 static dbus_bool_t
-_dbus_get_autolaunch_shm(DBusString *adress)
+_dbus_get_autolaunch_shm (DBusString *address, DBusString *shm_name)
 {
   HANDLE sharedMem;
-  const char *adr;
-  char szUserName[64];
-  DWORD dwUserNameSize = sizeof(szUserName);
-  char szDBusDaemonAddressInfo[128];
-
-  if( !GetUserName(szUserName, &dwUserNameSize) )
-      return FALSE;
-  _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
-            cDBusDaemonAddressInfo, szUserName);
+  char *shared_addr;
+  int i;
 
   // read shm
-  do {
+  for(i=0;i<20;++i) {
       // we know that dbus-daemon is available, so we wait until shm is available
-      sharedMem = OpenFileMapping( FILE_MAP_READ, FALSE, szDBusDaemonAddressInfo );
+      sharedMem = OpenFileMappingA( FILE_MAP_READ, FALSE, _dbus_string_get_const_data(shm_name));
       if( sharedMem == 0 )
           Sleep( 100 );
-  } while( sharedMem == 0 );
+      if ( sharedMem != 0)
+          break;
+  }
 
   if( sharedMem == 0 )
       return FALSE;
 
-  adr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
+  shared_addr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
 
-  if( adr == 0 )
+  if( !shared_addr )
       return FALSE;
 
-  _dbus_string_init( adress );
+  _dbus_string_init( address );
 
-  _dbus_string_append( adress, adr ); 
+  _dbus_string_append( address, shared_addr );
 
   // cleanup
-  UnmapViewOfFile( adr );
+  UnmapViewOfFile( shared_addr );
 
   CloseHandle( sharedMem );
 
@@ -5373,47 +3045,48 @@ _dbus_get_autolaunch_shm(DBusString *adress)
 }
 
 static dbus_bool_t
-_dbus_daemon_already_runs (DBusString *adress)
+_dbus_daemon_already_runs (DBusString *address, DBusString *shm_name, const char *scope)
 {
   HANDLE lock;
   HANDLE daemon;
+  DBusString mutex_name;
   dbus_bool_t bRet = TRUE;
-  char szUserName[64];
-  DWORD dwUserNameSize = sizeof(szUserName);
-  char szDBusDaemonMutex[128];
-
-  // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
-  lock = _dbus_global_lock( cUniqueDBusInitMutex );
 
-  if( !GetUserName(szUserName, &dwUserNameSize) )
+  if (!_dbus_get_mutex_name(&mutex_name,scope))
+    {
+      _dbus_string_free( &mutex_name );
       return FALSE;
-  _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
-            cDBusDaemonMutex, szUserName);
+    }
+
+  // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
+  lock = _dbus_global_lock( cUniqueDBusInitMutex );
 
   // do checks
-  daemon = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
+  daemon = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
   if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
     {
       ReleaseMutex (daemon);
       CloseHandle (daemon);
 
       _dbus_global_unlock( lock );
+      _dbus_string_free( &mutex_name );
       return FALSE;
     }
 
   // read shm
-  bRet = _dbus_get_autolaunch_shm( adress );
+  bRet = _dbus_get_autolaunch_shm( address, shm_name );
 
   // cleanup
   CloseHandle ( daemon );
 
   _dbus_global_unlock( lock );
+  _dbus_string_free( &mutex_name );
 
   return bRet;
 }
 
 dbus_bool_t
-_dbus_get_autolaunch_address (DBusString *address, 
+_dbus_get_autolaunch_address (const char *scope, DBusString *address,
                               DBusError *error)
 {
   HANDLE mutex;
@@ -5423,24 +3096,63 @@ _dbus_get_autolaunch_address (DBusString *address,
   LPSTR lpFile;
   char dbus_exe_path[MAX_PATH];
   char dbus_args[MAX_PATH * 2];
-
-  mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
+  const char * daemon_name = DBUS_DAEMON_NAME ".exe";
+  DBusString shm_name;
 
   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
 
-  if (_dbus_daemon_already_runs(address))
+  if (!_dbus_get_shm_name(&shm_name,scope))
+    {
+        dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not determine shm name");
+        return FALSE;
+    }
+
+  mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
+
+  if (_dbus_daemon_already_runs(address,&shm_name,scope))
     {
-        printf("dbus daemon already exists\n");
+        _dbus_verbose( "found running dbus daemon at %s\n",
+                       _dbus_string_get_const_data (&shm_name) );
         retval = TRUE;
         goto out;
     }
 
-  if (!SearchPathA(NULL, "dbus-daemon.exe", NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
+  if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
     {
-      printf ("could not find dbus-daemon executable\n");
-      goto out;
+      // Look in directory containing dbus shared library
+      HMODULE hmod;
+      char dbus_module_path[MAX_PATH];
+      DWORD rc;
+
+      _dbus_verbose( "did not found dbus daemon executable on default search path, "
+            "trying path where dbus shared library is located");
+
+      hmod = _dbus_win_get_dll_hmodule();
+      rc = GetModuleFileNameA(hmod, dbus_module_path, sizeof(dbus_module_path));
+      if (rc <= 0)
+        {
+          dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not retrieve dbus shared library file name");
+          retval = FALSE;
+          goto out;
+        }
+      else
+        {
+          char *ext_idx = strrchr(dbus_module_path, '\\');
+          if (ext_idx)
+          *ext_idx = '\0';
+          if (!SearchPathA(dbus_module_path, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
+            {
+              dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not find dbus-daemon executable");
+              retval = FALSE;
+              printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
+              printf ("or start the daemon manually\n\n");
+              goto out;
+            }
+          _dbus_verbose( "found dbus daemon executable at %s",dbus_module_path);
+        }
     }
 
+
   // Create process
   ZeroMemory( &si, sizeof(si) );
   si.cb = sizeof(si);
@@ -5449,19 +3161,21 @@ _dbus_get_autolaunch_address (DBusString *address,
   _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path,  " --session");
 
 //  argv[i] = "--config-file=bus\\session.conf";
-  printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
-  if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
+//  printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
+  if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
     {
-      retval = TRUE;
-
-      // Wait until started (see _dbus_get_autolaunch_shm())
-      WaitForInputIdle(pi.hProcess, INFINITE);
-
-      retval = _dbus_get_autolaunch_shm( address );
-    } else {
+      CloseHandle (pi.hThread);
+      CloseHandle (pi.hProcess);
+      retval = _dbus_get_autolaunch_shm( address, &shm_name );
+      if (retval == FALSE)
+        dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to get autolaunch address from launched dbus-daemon");
+    }
+  else
+    {
+      dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
       retval = FALSE;
     }
-  
+
 out:
   if (retval)
     _DBUS_ASSERT_ERROR_IS_CLEAR (error);
@@ -5488,9 +3202,24 @@ _dbus_make_file_world_readable(const DBusString *filename,
   return TRUE;
 }
 
+/**
+ * return the relocated DATADIR
+ *
+ * @returns relocated DATADIR static string
+ */
+
+static const char *
+_dbus_windows_get_datadir (void)
+{
+       return _dbus_replace_install_prefix(DBUS_DATADIR);
+}
+
+#undef DBUS_DATADIR
+#define DBUS_DATADIR _dbus_windows_get_datadir ()
 
-#define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
 
+#define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
+#define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
 
 /**
  * Returns the standard directories for a session bus to look for service 
@@ -5502,7 +3231,7 @@ _dbus_make_file_world_readable(const DBusString *filename,
  *
  * and
  *
- * DBUS_DATADIR
+ * relocated DBUS_DATADIR
  *
  * @param dirs the directory list we are returning
  * @returns #FALSE on OOM 
@@ -5517,8 +3246,46 @@ _dbus_get_standard_session_servicedirs (DBusList **dirs)
   if (!_dbus_string_init (&servicedir_path))
     return FALSE;
 
-  if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
-        goto oom;
+#ifdef DBUS_WINCE
+  {
+    /* On Windows CE, we adjust datadir dynamically to installation location.  */
+    const char *data_dir = _dbus_getenv ("DBUS_DATADIR");
+
+    if (data_dir != NULL)
+      {
+        if (!_dbus_string_append (&servicedir_path, data_dir))
+          goto oom;
+        
+        if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
+          goto oom;
+      }
+  }
+#else
+/*
+ the code for accessing services requires absolute base pathes
+ in case DBUS_DATADIR is relative make it absolute
+*/
+#ifdef DBUS_WIN
+  {
+    DBusString p;
+
+    _dbus_string_init_const (&p, DBUS_DATADIR);
+
+    if (!_dbus_path_is_absolute (&p))
+      {
+        char install_root[1000];
+        if (_dbus_get_install_root (install_root, sizeof(install_root)))
+          if (!_dbus_string_append (&servicedir_path, install_root))
+            goto oom;
+      }
+  }
+#endif
+  if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
+    goto oom;
+
+  if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
+    goto oom;
+#endif
 
   common_progs = _dbus_getenv ("CommonProgramFiles");
 
@@ -5544,7 +3311,30 @@ _dbus_get_standard_session_servicedirs (DBusList **dirs)
   return FALSE;
 }
 
-_DBUS_DEFINE_GLOBAL_LOCK (atomic);
+/**
+ * Returns the standard directories for a system bus to look for service
+ * activation files
+ *
+ * On UNIX this should be the standard xdg freedesktop.org data directories:
+ *
+ * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
+ *
+ * and
+ *
+ * DBUS_DATADIR
+ *
+ * On Windows there is no system bus and this function can return nothing.
+ *
+ * @param dirs the directory list we are returning
+ * @returns #FALSE on OOM
+ */
+
+dbus_bool_t
+_dbus_get_standard_system_servicedirs (DBusList **dirs)
+{
+  *dirs = NULL;
+  return TRUE;
+}
 
 /**
  * Atomically increments an integer
@@ -5557,6 +3347,7 @@ dbus_int32_t
 _dbus_atomic_inc (DBusAtomic *atomic)
 {
   // +/- 1 is needed here!
+  // no volatile argument with mingw
   return InterlockedIncrement (&atomic->value) - 1;
 }
 
@@ -5571,10 +3362,34 @@ dbus_int32_t
 _dbus_atomic_dec (DBusAtomic *atomic)
 {
   // +/- 1 is needed here!
+  // no volatile argument with mingw
   return InterlockedDecrement (&atomic->value) + 1;
 }
 
-#endif /* asserts or tests enabled */
+/**
+ * Atomically get the value of an integer. It may change at any time
+ * thereafter, so this is mostly only useful for assertions.
+ *
+ * @param atomic pointer to the integer to get
+ * @returns the value at this moment
+ */
+dbus_int32_t
+_dbus_atomic_get (DBusAtomic *atomic)
+{
+  /* In this situation, GLib issues a MemoryBarrier() and then returns
+   * atomic->value. However, mingw from mingw.org (not to be confused with
+   * mingw-w64 from mingw-w64.sf.net) does not have MemoryBarrier in its
+   * headers, so we have to get a memory barrier some other way.
+   *
+   * InterlockedIncrement is older, and is documented on MSDN to be a full
+   * memory barrier, so let's use that.
+   */
+  long dummy = 0;
+
+  InterlockedExchange (&dummy, 1);
+
+  return atomic->value;
+}
 
 /**
  * Called when the bus daemon is signaled to reload its configuration; any
@@ -5586,12 +3401,6 @@ _dbus_atomic_dec (DBusAtomic *atomic)
 void
 _dbus_flush_caches (void)
 {
-
-}
-
-dbus_bool_t _dbus_windows_user_is_process_owner (const char *windows_sid)
-{
-    return TRUE;
 }
 
 /**
@@ -5603,37 +3412,50 @@ dbus_bool_t _dbus_windows_user_is_process_owner (const char *windows_sid)
 dbus_bool_t
 _dbus_get_is_errno_eagain_or_ewouldblock (void)
 {
-  return errno == EAGAIN || errno == EWOULDBLOCK;
+  return errno == WSAEWOULDBLOCK;
 }
 
 /**
  * return the absolute path of the dbus installation 
  *
- * @param s buffer for installation path
+ * @param prefix buffer for installation path
  * @param len length of buffer
  * @returns #FALSE on failure
  */
-dbus_bool_t 
-_dbus_get_install_root(char *s, int len)
-{
-  char *p = NULL;
-  int ret = GetModuleFileName(NULL,s,len);
-  if ( ret == 0 
-    || ret == len && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
-    {
-      *s = '\0';
-      return FALSE;
-    }
-  else if ((p = strstr(s,"\\bin\\")))
-    {
-      *(p+1)= '\0';
-      return TRUE;
-    }
-  else
-    {
-      *s = '\0';
-      return FALSE;
+dbus_bool_t
+_dbus_get_install_root(char *prefix, int len)
+{
+    //To find the prefix, we cut the filename and also \bin\ if present
+    DWORD pathLength;
+    char *lastSlash;
+    SetLastError( 0 );
+    pathLength = GetModuleFileNameA(_dbus_win_get_dll_hmodule(), prefix, len);
+    if ( pathLength == 0 || GetLastError() != 0 ) {
+        *prefix = '\0';
+        return FALSE;
+    }
+    lastSlash = _mbsrchr(prefix, '\\');
+    if (lastSlash == NULL) {
+        *prefix = '\0';
+        return FALSE;
     }
+    //cut off binary name
+    lastSlash[1] = 0;
+
+    //cut possible "\\bin"
+
+    //this fails if we are in a double-byte system codepage and the
+    //folder's name happens to end with the *bytes*
+    //"\\bin"... (I.e. the second byte of some Han character and then
+    //the Latin "bin", but that is not likely I think...
+    if (lastSlash - prefix >= 4 && strnicmp(lastSlash - 4, "\\bin", 4) == 0)
+        lastSlash[-3] = 0;
+    else if (lastSlash - prefix >= 10 && strnicmp(lastSlash - 10, "\\bin\\debug", 10) == 0)
+        lastSlash[-9] = 0;
+    else if (lastSlash - prefix >= 12 && strnicmp(lastSlash - 12, "\\bin\\release", 12) == 0)
+        lastSlash[-11] = 0;
+
+    return TRUE;
 }
 
 /** 
@@ -5641,7 +3463,9 @@ _dbus_get_install_root(char *s, int len)
   the following path layout 
     install-root/
       bin/dbus-daemon[d].exe
-      etc/<config-file>.conf 
+      etc/<config-file>.conf *or* etc/dbus-1/<config-file>.conf
+      (the former above is what dbus4win uses, the latter above is
+      what a "normal" Unix-style "make install" uses)
 
     build-root/
       bin/dbus-daemon[d].exe
@@ -5656,8 +3480,10 @@ _dbus_get_config_file_name(DBusString *config_file, char *s)
   if (!_dbus_get_install_root(path,path_size))
     return FALSE;
 
-  strcat_s(path,path_size,"etc\\");
-  strcat_s(path,path_size,s);
+  if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
+    return FALSE;
+  strcat(path,"etc\\");
+  strcat(path,s);
   if (_dbus_file_exists(path)) 
     {
       // find path from executable 
@@ -5668,14 +3494,31 @@ _dbus_get_config_file_name(DBusString *config_file, char *s)
     {
       if (!_dbus_get_install_root(path,path_size))
         return FALSE;
-      strcat_s(path,path_size,"bus\\");
-      strcat_s(path,path_size,s);
+      if(strlen(s) + 11 + strlen(path) > sizeof(path)-2)
+        return FALSE;
+      strcat(path,"etc\\dbus-1\\");
+      strcat(path,s);
   
       if (_dbus_file_exists(path)) 
         {
           if (!_dbus_string_append (config_file, path))
             return FALSE;
         }
+      else
+        {
+          if (!_dbus_get_install_root(path,path_size))
+            return FALSE;
+          if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
+            return FALSE;
+          strcat(path,"bus\\");
+          strcat(path,s);
+          
+          if (_dbus_file_exists(path)) 
+            {
+              if (!_dbus_string_append (config_file, path))
+                return FALSE;
+            }
+        }
     }
   return TRUE;
 }    
@@ -5706,6 +3549,17 @@ _dbus_append_session_config_file (DBusString *str)
   return _dbus_get_config_file_name(str, "session.conf");
 }
 
+/* See comment in dbus-sysdeps-unix.c */
+dbus_bool_t
+_dbus_lookup_session_address (dbus_bool_t *supported,
+                              DBusString  *address,
+                              DBusError   *error)
+{
+  /* Probably fill this in with something based on COM? */
+  *supported = FALSE;
+  return TRUE;
+}
+
 /**
  * Appends the directory in which a keyring for the given credentials
  * should be stored.  The credentials should have either a Windows or
@@ -5725,8 +3579,8 @@ _dbus_append_keyring_directory_for_credentials (DBusString      *directory,
 {
   DBusString homedir;
   DBusString dotdir;
-  dbus_uid_t uid;
   const char *homepath;
+  const char *homedrive;
 
   _dbus_assert (credentials != NULL);
   _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
@@ -5734,13 +3588,19 @@ _dbus_append_keyring_directory_for_credentials (DBusString      *directory,
   if (!_dbus_string_init (&homedir))
     return FALSE;
 
+  homedrive = _dbus_getenv("HOMEDRIVE");
+  if (homedrive != NULL && *homedrive != '\0')
+    {
+      _dbus_string_append(&homedir,homedrive);
+    }
+
   homepath = _dbus_getenv("HOMEPATH");
   if (homepath != NULL && *homepath != '\0')
     {
       _dbus_string_append(&homedir,homepath);
     }
   
-#ifdef DBUS_BUILD_TESTS
+#ifdef DBUS_ENABLE_EMBEDDED_TESTS
   {
     const char *override;
     
@@ -5766,7 +3626,15 @@ _dbus_append_keyring_directory_for_credentials (DBusString      *directory,
   }
 #endif
 
-  _dbus_string_init_const (&dotdir, ".dbus-keyrings");
+#ifdef DBUS_WINCE
+  /* It's not possible to create a .something directory in Windows CE
+     using the file explorer.  */
+#define KEYRING_DIR "dbus-keyrings"
+#else
+#define KEYRING_DIR ".dbus-keyrings"
+#endif
+
+  _dbus_string_init_const (&dotdir, KEYRING_DIR);
   if (!_dbus_concat_dir_and_file (&homedir,
                                   &dotdir))
     goto failed;
@@ -5784,5 +3652,257 @@ _dbus_append_keyring_directory_for_credentials (DBusString      *directory,
   return FALSE;
 }
 
+/** Checks if a file exists
+*
+* @param file full path to the file
+* @returns #TRUE if file exists
+*/
+dbus_bool_t 
+_dbus_file_exists (const char *file)
+{
+  DWORD attributes = GetFileAttributesA (file);
+
+  if (attributes != INVALID_FILE_ATTRIBUTES && GetLastError() != ERROR_PATH_NOT_FOUND)
+    return TRUE;
+  else
+    return FALSE;  
+}
+
+/**
+ * A wrapper around strerror() because some platforms
+ * may be lame and not have strerror().
+ *
+ * @param error_number errno.
+ * @returns error description.
+ */
+const char*
+_dbus_strerror (int error_number)
+{
+#ifdef DBUS_WINCE
+  // TODO
+  return "unknown";
+#else
+  const char *msg;
+
+  switch (error_number)
+    {
+    case WSAEINTR:
+      return "Interrupted function call";
+    case WSAEACCES:
+      return "Permission denied";
+    case WSAEFAULT:
+      return "Bad address";
+    case WSAEINVAL:
+      return "Invalid argument";
+    case WSAEMFILE:
+      return "Too many open files";
+    case WSAEWOULDBLOCK:
+      return "Resource temporarily unavailable";
+    case WSAEINPROGRESS:
+      return "Operation now in progress";
+    case WSAEALREADY:
+      return "Operation already in progress";
+    case WSAENOTSOCK:
+      return "Socket operation on nonsocket";
+    case WSAEDESTADDRREQ:
+      return "Destination address required";
+    case WSAEMSGSIZE:
+      return "Message too long";
+    case WSAEPROTOTYPE:
+      return "Protocol wrong type for socket";
+    case WSAENOPROTOOPT:
+      return "Bad protocol option";
+    case WSAEPROTONOSUPPORT:
+      return "Protocol not supported";
+    case WSAESOCKTNOSUPPORT:
+      return "Socket type not supported";
+    case WSAEOPNOTSUPP:
+      return "Operation not supported";
+    case WSAEPFNOSUPPORT:
+      return "Protocol family not supported";
+    case WSAEAFNOSUPPORT:
+      return "Address family not supported by protocol family";
+    case WSAEADDRINUSE:
+      return "Address already in use";
+    case WSAEADDRNOTAVAIL:
+      return "Cannot assign requested address";
+    case WSAENETDOWN:
+      return "Network is down";
+    case WSAENETUNREACH:
+      return "Network is unreachable";
+    case WSAENETRESET:
+      return "Network dropped connection on reset";
+    case WSAECONNABORTED:
+      return "Software caused connection abort";
+    case WSAECONNRESET:
+      return "Connection reset by peer";
+    case WSAENOBUFS:
+      return "No buffer space available";
+    case WSAEISCONN:
+      return "Socket is already connected";
+    case WSAENOTCONN:
+      return "Socket is not connected";
+    case WSAESHUTDOWN:
+      return "Cannot send after socket shutdown";
+    case WSAETIMEDOUT:
+      return "Connection timed out";
+    case WSAECONNREFUSED:
+      return "Connection refused";
+    case WSAEHOSTDOWN:
+      return "Host is down";
+    case WSAEHOSTUNREACH:
+      return "No route to host";
+    case WSAEPROCLIM:
+      return "Too many processes";
+    case WSAEDISCON:
+      return "Graceful shutdown in progress";
+    case WSATYPE_NOT_FOUND:
+      return "Class type not found";
+    case WSAHOST_NOT_FOUND:
+      return "Host not found";
+    case WSATRY_AGAIN:
+      return "Nonauthoritative host not found";
+    case WSANO_RECOVERY:
+      return "This is a nonrecoverable error";
+    case WSANO_DATA:
+      return "Valid name, no data record of requested type";
+    case WSA_INVALID_HANDLE:
+      return "Specified event object handle is invalid";
+    case WSA_INVALID_PARAMETER:
+      return "One or more parameters are invalid";
+    case WSA_IO_INCOMPLETE:
+      return "Overlapped I/O event object not in signaled state";
+    case WSA_IO_PENDING:
+      return "Overlapped operations will complete later";
+    case WSA_NOT_ENOUGH_MEMORY:
+      return "Insufficient memory available";
+    case WSA_OPERATION_ABORTED:
+      return "Overlapped operation aborted";
+#ifdef WSAINVALIDPROCTABLE
+
+    case WSAINVALIDPROCTABLE:
+      return "Invalid procedure table from service provider";
+#endif
+#ifdef WSAINVALIDPROVIDER
+
+    case WSAINVALIDPROVIDER:
+      return "Invalid service provider version number";
+#endif
+#ifdef WSAPROVIDERFAILEDINIT
+
+    case WSAPROVIDERFAILEDINIT:
+      return "Unable to initialize a service provider";
+#endif
+
+    case WSASYSCALLFAILURE:
+      return "System call failure";
+    }
+  msg = strerror (error_number);
+  if (msg == NULL)
+    msg = "unknown";
+
+  return msg;
+#endif //DBUS_WINCE
+}
+
+/**
+ * Assigns an error name and message corresponding to a Win32 error
+ * code to a DBusError. Does nothing if error is #NULL.
+ *
+ * @param error the error.
+ * @param code the Win32 error code
+ */
+void
+_dbus_win_set_error_from_win_error (DBusError *error,
+                                    int        code)
+{
+  char *msg;
+
+  /* As we want the English message, use the A API */
+  FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
+                  FORMAT_MESSAGE_IGNORE_INSERTS |
+                  FORMAT_MESSAGE_FROM_SYSTEM,
+                  NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
+                  (LPSTR) &msg, 0, NULL);
+  if (msg)
+    {
+      char *msg_copy;
+
+      msg_copy = dbus_malloc (strlen (msg));
+      strcpy (msg_copy, msg);
+      LocalFree (msg);
+
+      dbus_set_error (error, "win32.error", "%s", msg_copy);
+    }
+  else
+    dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
+}
+
+void
+_dbus_win_warn_win_error (const char *message,
+                          int         code)
+{
+  DBusError error;
+
+  dbus_error_init (&error);
+  _dbus_win_set_error_from_win_error (&error, code);
+  _dbus_warn ("%s: %s\n", message, error.message);
+  dbus_error_free (&error);
+}
+
+/**
+ * Removes a directory; Directory must be empty
+ *
+ * @param filename directory filename
+ * @param error initialized error object
+ * @returns #TRUE on success
+ */
+dbus_bool_t
+_dbus_delete_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 (RemoveDirectoryA (filename_c) == 0)
+    {
+      char *emsg = _dbus_win_error_string (GetLastError ());
+      dbus_set_error (error, _dbus_win_error_from_last_error (),
+                      "Failed to remove directory %s: %s",
+                      filename_c, emsg);
+      _dbus_win_free_error_string (emsg);
+      return FALSE;
+    }
+
+  return TRUE;
+}
+
+/**
+ * Checks whether the filename is an absolute path
+ *
+ * @param filename the filename
+ * @returns #TRUE if an absolute path
+ */
+dbus_bool_t
+_dbus_path_is_absolute (const DBusString *filename)
+{
+  if (_dbus_string_get_length (filename) > 0)
+    return _dbus_string_get_byte (filename, 1) == ':'
+           || _dbus_string_get_byte (filename, 0) == '\\'
+           || _dbus_string_get_byte (filename, 0) == '/';
+  else
+    return FALSE;
+}
+
+dbus_bool_t
+_dbus_check_setuid (void)
+{
+  return FALSE;
+}
+
 /** @} end of sysdeps-win */
 /* tests in dbus-sysdeps-util.c */
+