Revert "Remove refcounting from DBusAuth and DBusAuthorization"
[platform/upstream/dbus.git] / dbus / dbus-sysdeps-win.c
index acdd7bd..38758bd 100644 (file)
@@ -4,9 +4,9 @@
  * 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 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
  * 
@@ -26,7 +26,7 @@
  *
  */
 
-#undef open
+#include <config.h>
 
 #define STRSAFE_NO_DEPRECATE
 
 #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 <ws2tcpip.h>
 #include <wincrypt.h>
+#include <iphlpapi.h>
 
-#include <fcntl.h>
+/* 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);
 
-#include <process.h>
 #include <stdio.h>
-#include <io.h>
 
 #include <string.h>
+#if HAVE_ERRNO_H
 #include <errno.h>
+#endif
+#ifndef DBUS_WINCE
+#include <mbstring.h>
 #include <sys/stat.h>
 #include <sys/types.h>
+#endif
+
+#ifdef HAVE_WS2TCPIP_H
+/* getaddrinfo for Windows CE (and Windows).  */
+#include <ws2tcpip.h>
+#endif
 
 #ifdef HAVE_WSPIAPI_H
 // needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
 
 typedef int socklen_t;
 
+
+void
+_dbus_win_set_errno (int err)
+{
+#ifdef DBUS_WINCE
+  SetLastError (err);
+#else
+  errno = err;
+#endif
+}
+
+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;
+
 /**
- * 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
+ * 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
  */
-int
-_dbus_pipe_write (DBusPipe         *pipe,
-                  const DBusString *buffer,
-                  int               start,
-                  int               len,
-                  DBusError        *error)
+static BOOL
+load_ex_ip_helper_procedures(void)
 {
-  int written;
-  const char *buffer_c = _dbus_string_get_const_data (buffer);
+  HMODULE hModule = LoadLibrary ("iphlpapi.dll");
+  if (hModule == NULL)
+    {
+      _dbus_verbose ("could not load iphlpapi.dll\n");
+      return FALSE;
+    }
 
-  written = _write (pipe->fd_or_handle, buffer_c + start, len);
-  if (written < 0)
+  lpfnAllocateAndGetTcpExTableFromStack = (ProcAllocateAndGetTcpExtTableFromStack)GetProcAddress (hModule, "AllocateAndGetTcpExTableFromStack");
+  if (lpfnAllocateAndGetTcpExTableFromStack == NULL)
     {
-      dbus_set_error (error, DBUS_ERROR_FAILED,
-                      "Writing to pipe: %s\n",
-                      strerror (errno));
+      _dbus_verbose ("could not find function AllocateAndGetTcpExTableFromStack in iphlpapi.dll\n");
+      return FALSE;
+    }
+  return TRUE;
+}
+
+/**
+ * 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)
+{
+  dbus_pid_t result;
+  DWORD errorCode, size, i;
+  MIB_TCPTABLE_OWNER_PID *tcp_table;
+
+  if ((errorCode =
+       GetExtendedTcpTable (NULL, &size, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0)) == ERROR_INSUFFICIENT_BUFFER)
+    {
+      tcp_table = (MIB_TCPTABLE_OWNER_PID *) dbus_malloc (size);
+      if (tcp_table == NULL)
+        {
+          _dbus_verbose ("Error allocating memory\n");
+          return 0;
+        }
+    }
+  else
+    {
+      _dbus_verbose ("unexpected error returned from GetExtendedTcpTable %d\n", errorCode);
+      return 0;
+    }
+
+  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;
+    }
+
+  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;
     }
-  return written;
+
+  dbus_free (tcp_table);
+  _dbus_verbose ("got pid %d\n", (int)result);
+  return result;
 }
 
 /**
- * close a pipe.
- *
- * @param pipe the pipe instance
- * @param error return location for an error
- * @returns #FALSE if error is set
+ * 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_close  (DBusPipe         *pipe,
-                   DBusError        *error)
+static dbus_pid_t
+get_pid_from_tcp_ex_table(int peer_port)
 {
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+  dbus_pid_t result;
+  DWORD errorCode, i;
+  PMIB_TCPTABLE_EX tcp_table = NULL;
 
-  if (_close (pipe->fd_or_handle) < 0)
+  if (!load_ex_ip_helper_procedures ())
     {
-      return -1;
+      _dbus_verbose
+        ("Error not been able to load iphelper procedures\n");
+      return 0;
+    }
+
+  errorCode = lpfnAllocateAndGetTcpExTableFromStack (&tcp_table, TRUE, GetProcessHeap(), 0, 2);
+
+  if (errorCode != NO_ERROR)
+    {
+      _dbus_verbose
+        ("Error not been able to call AllocateAndGetTcpExTableFromStack()\n");
+      return 0;
+    }
+
+  result = 0;
+  for (i = 0; i < tcp_table->dwNumEntries; i++)
+    {
+      _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;
+        }
+    }
+
+  HeapFree (GetProcessHeap(), 0, tcp_table);
+  _dbus_verbose ("got pid %d\n", (int)result);
+  return result;
+}
+
+/**
+ * @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
+ */
+static dbus_pid_t
+_dbus_get_peer_pid_from_tcp_handle (int handle)
+{
+  struct sockaddr_storage addr;
+  socklen_t len = sizeof (addr);
+  int peer_port;
+
+  dbus_pid_t result;
+  dbus_bool_t is_localhost = FALSE;
+
+  getpeername (handle, (struct sockaddr *) &addr, &len);
+
+  if (addr.ss_family == AF_INET)
+    {
+      struct sockaddr_in *s = (struct sockaddr_in *) &addr;
+      peer_port = ntohs (s->sin_port);
+      is_localhost = (ntohl (s->sin_addr.s_addr) == INADDR_LOOPBACK);
+    }
+  else if (addr.ss_family == AF_INET6)
+    {
+      _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_pipe_invalidate (pipe);
+      _dbus_verbose ("no idea what address family %d is\n", addr.ss_family);
+      return 0;
+    }
+
+  if (!is_localhost)
+    {
+      _dbus_verbose ("could not fetch process id from remote process\n");
+      return 0;
+    }
+
+  if (peer_port == 0)
+    {
+      _dbus_verbose
+        ("Error not been able to fetch tcp peer port from connection\n");
       return 0;
     }
+
+  _dbus_verbose ("trying to get peers pid");
+
+  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;
+}
+
+/* Convert GetLastError() to a dbus error.  */
+const char*
+_dbus_win_error_from_last_error (void)
+{
+  switch (GetLastError())
+    {
+    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;
+
+    case ERROR_NOT_ENOUGH_MEMORY:
+      return DBUS_ERROR_NO_MEMORY;
+
+    case ERROR_FILE_EXISTS:
+      return DBUS_ERROR_FILE_EXISTS;
+
+    case ERROR_FILE_NOT_FOUND:
+    case ERROR_PATH_NOT_FOUND:
+      return DBUS_ERROR_FILE_NOT_FOUND;
+    }
+  
+  return DBUS_ERROR_FAILED;
+}
+
+
+char*
+_dbus_win_error_string (int error_number)
+{
+  char *msg;
+
+  FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
+                  FORMAT_MESSAGE_IGNORE_INSERTS |
+                  FORMAT_MESSAGE_FROM_SYSTEM,
+                  NULL, error_number, 0,
+                  (LPSTR) &msg, 0, NULL);
+
+  if (msg[strlen (msg) - 1] == '\n')
+    msg[strlen (msg) - 1] = '\0';
+  if (msg[strlen (msg) - 1] == '\r')
+    msg[strlen (msg) - 1] = '\0';
+
+  return msg;
+}
+
+void
+_dbus_win_free_error_string (char *string)
+{
+  LocalFree (string);
 }
 
 /**
@@ -143,14 +369,16 @@ _dbus_pipe_close  (DBusPipe         *pipe,
  * 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               fd,
                    DBusString       *buffer,
@@ -166,7 +394,7 @@ _dbus_read_socket (int               fd,
 
   if (!_dbus_string_lengthen (buffer, count))
     {
-      errno = ENOMEM;
+      _dbus_win_set_errno (ENOMEM);
       return -1;
     }
 
@@ -180,7 +408,7 @@ _dbus_read_socket (int               fd,
   if (bytes_read == SOCKET_ERROR)
        {
          DBUS_SOCKET_SET_ERRNO();
-         _dbus_verbose ("recv: failed: %s\n", _dbus_strerror (errno));
+         _dbus_verbose ("recv: failed: %s (%d)\n", _dbus_strerror (errno), errno);
          bytes_read = -1;
        }
        else
@@ -240,7 +468,7 @@ _dbus_write_socket (int               fd,
   if (bytes_written == SOCKET_ERROR)
     {
       DBUS_SOCKET_SET_ERRNO();
-      _dbus_verbose ("send: failed: %s\n", _dbus_strerror (errno));
+      _dbus_verbose ("send: failed: %s\n", _dbus_strerror_from_errno ());
       bytes_written = -1;
     }
     else
@@ -281,7 +509,7 @@ _dbus_close_socket (int        fd,
         
       dbus_set_error (error, _dbus_error_from_errno (errno),
                       "Could not close socket: socket=%d, , %s",
-                      fd, _dbus_strerror (errno));
+                      fd, _dbus_strerror_from_errno ());
       return FALSE;
     }
   _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
@@ -294,42 +522,23 @@ _dbus_close_socket (int        fd,
  * 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.
  */
@@ -343,9 +552,10 @@ _dbus_set_fd_nonblocking (int             handle,
 
   if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
     {
-      dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
+      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 (WSAGetLastError ()));
+                      _dbus_strerror_from_errno ());
       return FALSE;
     }
 
@@ -422,10 +632,10 @@ _dbus_write_socket_two (int               fd,
                 NULL, 
                 NULL);
                 
-  if (rc < 0)
+  if (rc == SOCKET_ERROR)
     {
       DBUS_SOCKET_SET_ERRNO ();
-      _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
+      _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror_from_errno ());
       bytes_written = -1;
     }
   else
@@ -437,6 +647,12 @@ _dbus_write_socket_two (int               fd,
   return bytes_written;
 }
 
+dbus_bool_t
+_dbus_socket_is_invalid (int fd)
+{
+    return fd == INVALID_SOCKET ? TRUE : FALSE;
+}
+
 #if 0
 
 /**
@@ -520,9 +736,12 @@ int _dbus_printf_string_upper_bound (const char *format,
   char buf[1024];
   int bufsize;
   int len;
+  va_list args_copy;
 
   bufsize = sizeof (buf);
-  len = _vsnprintf (buf, bufsize - 1, format, args);
+  DBUS_VA_COPY (args_copy, args);
+  len = _vsnprintf (buf, bufsize - 1, format, args_copy);
+  va_end (args_copy);
 
   while (len == -1) /* try again */
     {
@@ -531,7 +750,13 @@ int _dbus_printf_string_upper_bound (const char *format,
       bufsize *= 2;
 
       p = malloc (bufsize);
-      len = _vsnprintf (p, bufsize - 1, format, args);
+
+      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);
     }
 
@@ -704,15 +929,6 @@ out1:
 /** @} end of sysdeps-win */
 
 
-/** Gets our UID
- * @returns process UID
- */
-dbus_uid_t
-_dbus_getuid (void)
-{
-       return DBUS_UID_UNSET;
-}
-
 /**
  * The only reason this is separate from _dbus_getpid() is to allow it
  * on Windows for logging but not for other purposes.
@@ -725,20 +941,56 @@ _dbus_pid_for_log (void)
   return _dbus_getpid ();
 }
 
+#ifndef DBUS_WINCE
+
+static BOOL is_winxp_sp3_or_lower()
+{
+   OSVERSIONINFOEX osvi;
+   DWORDLONG dwlConditionMask = 0;
+   int op=VER_LESS_EQUAL;
+
+   // Initialize the OSVERSIONINFOEX structure.
+
+   ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
+   osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
+   osvi.dwMajorVersion = 5;
+   osvi.dwMinorVersion = 1;
+   osvi.wServicePackMajor = 3;
+   osvi.wServicePackMinor = 0;
+
+   // Initialize the condition mask.
+
+   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 );
+
+   // Perform the test.
+
+   return VerifyVersionInfo(
+      &osvi,
+      VER_MAJORVERSION | VER_MINORVERSION |
+      VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR,
+      dwlConditionMask);
+}
+
 /** Gets our SID
- * @param points to sid buffer, need to be freed with LocalFree()
+ * @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_bool_t
-_dbus_getsid(char **sid)
+static dbus_bool_t
+_dbus_getsid(char **sid, dbus_pid_t process_id)
 {
-  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)) 
+
+  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;
@@ -766,38 +1018,15 @@ _dbus_getsid(char **sid)
   retval = TRUE;
 
 failed:
-  if (process_token != NULL)
+  CloseHandle (process_handle);
+  if (process_token != INVALID_HANDLE_VALUE)
     CloseHandle (process_token);
 
-  _dbus_verbose("_dbus_getsid() returns %d\n",retval);
+  _dbus_verbose("_dbus_getsid() got '%s' and returns %d\n", *sid, retval);
   return retval;
 }
-
-
-#ifdef DBUS_BUILD_TESTS
-/** Gets our GID
- * @returns process GID
- */
-dbus_gid_t
-_dbus_getgid (void)
-{
-       return DBUS_GID_UNSET;
-}
-
-#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
@@ -808,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
@@ -829,8 +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;
 
   _dbus_win_startup_winsock ();
 
@@ -841,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;
@@ -866,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;
@@ -879,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)
     {
@@ -914,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)
         {
@@ -973,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;
 }
@@ -986,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;
@@ -1016,7 +1188,6 @@ _dbus_poll (DBusPollFD *fds,
   msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
   for (i = 0; i < n_fds; i++)
     {
-      static dbus_bool_t warned = FALSE;
       DBusPollFD *fdp = &fds[i];
 
 
@@ -1064,8 +1235,8 @@ _dbus_poll (DBusPollFD *fds,
   if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
     {
       DBUS_SOCKET_SET_ERRNO ();
-      if (errno != EWOULDBLOCK)
-        _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", strerror (errno));
+      if (errno != WSAEWOULDBLOCK)
+        _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror_from_errno ());
       ret = -1;
     }
   else if (ready == WSA_WAIT_TIMEOUT)
@@ -1131,15 +1302,9 @@ _dbus_poll (DBusPollFD *fds,
     free(pEvents);
 
   return ret;
-}
 
-#else   // USE_CHRIS_IMPL
+#else   /* USE_CHRIS_IMPL */
 
-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;
@@ -1160,7 +1325,6 @@ _dbus_poll (DBusPollFD *fds,
   msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
   for (i = 0; i < n_fds; i++)
     {
-      static dbus_bool_t warned = FALSE;
       DBusPollFD *fdp = &fds[i];
 
 
@@ -1198,18 +1362,17 @@ _dbus_poll (DBusPollFD *fds,
       max_fd = MAX (max_fd, fdp->fd);
     }
 
+  // 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");
@@ -1254,10 +1417,9 @@ _dbus_poll (DBusPollFD *fds,
           }
       }
   return ready;
+#endif  /* USE_CHRIS_IMPL */
 }
 
-#endif  // USE_CHRIS_IMPL
-
 
 
 
@@ -1320,6 +1482,16 @@ _dbus_connect_tcp_socket (const char     *host,
                           const char     *family,
                           DBusError      *error)
 {
+  return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
+}
+
+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;
@@ -1328,21 +1500,6 @@ _dbus_connect_tcp_socket (const char     *host,
 
   _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));
-
-      return -1;
-    }
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR(error);
-
   _DBUS_ZERO (hints);
 
   if (!family)
@@ -1354,7 +1511,7 @@ _dbus_connect_tcp_socket (const char     *host,
   else
     {
       dbus_set_error (error,
-                      _dbus_error_from_errno (errno),
+                      DBUS_ERROR_INVALID_ARGS,
                       "Unknown address family %s", family);
       return -1;
     }
@@ -1366,34 +1523,35 @@ _dbus_connect_tcp_socket (const char     *host,
   hints.ai_flags = 0;
 #endif
 
-  if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
+  if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
     {
       dbus_set_error (error,
-                      _dbus_error_from_errno (errno),
+                      _dbus_error_from_errno (res),
                       "Failed to lookup host/port: \"%s:%s\": %s (%d)",
-                      host, port, gai_strerror(res), res);
-      closesocket (fd);
+                      host, port, _dbus_strerror(res), res);
       return -1;
     }
 
   tmp = ai;
   while (tmp)
     {
-      if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
+      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);
-      dbus_set_error (error,
-                      _dbus_error_from_errno (errno),
-                         "Failed to open socket: %s",
-                         _dbus_strerror (errno));
           return -1;
         }
       _DBUS_ASSERT_ERROR_IS_CLEAR(error);
 
-      if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
+      if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
         {
+          DBUS_SOCKET_SET_ERRNO ();
           closesocket(fd);
-      fd = -1;
+          fd = -1;
           tmp = tmp->ai_next;
           continue;
         }
@@ -1407,26 +1565,44 @@ _dbus_connect_tcp_socket (const char     *host,
       dbus_set_error (error,
                       _dbus_error_from_errno (errno),
                       "Failed to connect to socket \"%s:%s\" %s",
-                      host, port, _dbus_strerror(errno));
+                      host, port, _dbus_strerror_from_errno ());
       return -1;
     }
 
-
-  if (!_dbus_set_fd_nonblocking (fd, error))
+  if (noncefile != NULL)
     {
-      closesocket (fd);
-      fd = -1;
+      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;
+        }
+
+      ret = _dbus_send_nonce (fd, &noncefileStr, error);
+
+      _dbus_string_free (&noncefileStr);
+
+      if (!ret)
+        {
+          closesocket (fd);
+          return -1;
+        }
+    }
 
+  _dbus_fd_set_close_on_exec (fd);
+
+  if (!_dbus_set_fd_nonblocking (fd, error))
+    {
+      closesocket (fd);
       return -1;
     }
 
   return fd;
 }
 
-
-void
-_dbus_daemon_init(const char *host, dbus_uint32_t port);
-
 /**
  * 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
@@ -1454,6 +1630,16 @@ _dbus_listen_tcp_socket (const char     *host,
   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);
 
@@ -1470,7 +1656,7 @@ _dbus_listen_tcp_socket (const char     *host,
   else
     {
       dbus_set_error (error,
-                      _dbus_error_from_errno (errno),
+                      DBUS_ERROR_INVALID_ARGS,
                       "Unknown address family %s", family);
       return -1;
     }
@@ -1487,9 +1673,9 @@ _dbus_listen_tcp_socket (const char     *host,
   if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
     {
       dbus_set_error (error,
-                      _dbus_error_from_errno (errno),
+                      _dbus_error_from_errno (res),
                       "Failed to lookup host/port: \"%s:%s\": %s (%d)",
-                      host ? host : "*", port, gai_strerror(res), res);
+                      host ? host : "*", port, _dbus_strerror(res), res);
       return -1;
     }
 
@@ -1497,43 +1683,45 @@ _dbus_listen_tcp_socket (const char     *host,
   while (tmp)
     {
       int fd = -1, *newlisten_fd;
-      if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
+      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 (errno));
+                         _dbus_strerror_from_errno ());
           goto failed;
         }
       _DBUS_ASSERT_ERROR_IS_CLEAR(error);
 
       if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
         {
-          closesocket (fd);
+          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 (errno));
+                          host ? host : "*", port, _dbus_strerror_from_errno ());
+          closesocket (fd);
           goto failed;
     }
 
       if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
         {
-          closesocket (fd);
+          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 (errno));
+                          host ? host : "*", port, _dbus_strerror_from_errno ());
+          closesocket (fd);
           goto failed;
         }
 
       newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
       if (!newlisten_fd)
-    {
+        {
           closesocket (fd);
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                          "Failed to allocate file handle array: %s",
-                          _dbus_strerror (errno));
+          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++;
@@ -1546,15 +1734,16 @@ _dbus_listen_tcp_socket (const char     *host,
              to use the same port */
           if (!port || !strcmp(port, "0"))
             {
-              sockaddr_gen addr;
+              mysockaddr_gen addr;
               socklen_t addrlen = sizeof(addr);
               char portbuf[10];
 
-              if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                                  "Failed to resolve port \"%s:%s\": %s (%d)",
-                                  host ? host : "*", port, gai_strerror(res), res);
+              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 );
@@ -1562,7 +1751,7 @@ _dbus_listen_tcp_socket (const char     *host,
                 {
                   dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
                   goto failed;
-    }
+                }
 
               /* Release current address list & redo lookup */
               port = _dbus_string_get_const_data(retport);
@@ -1586,18 +1775,18 @@ _dbus_listen_tcp_socket (const char     *host,
 
   if (!nlisten_fd)
     {
-      errno = WSAEADDRINUSE;
+      _dbus_win_set_errno (WSAEADDRINUSE);
       dbus_set_error (error, _dbus_error_from_errno (errno),
                       "Failed to bind socket \"%s:%s\": %s",
-                      host ? host : "*", port, _dbus_strerror (errno));
+                      host ? host : "*", port, _dbus_strerror_from_errno ());
       return -1;
     }
 
   sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
-  _dbus_daemon_init(host, port_num);
 
   for (i = 0 ; i < nlisten_fd ; i++)
     {
+      _dbus_fd_set_close_on_exec (listen_fd[i]);
       if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
         {
           goto failed;
@@ -1689,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)
@@ -1714,13 +1903,13 @@ again:
  * 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
@@ -1732,22 +1921,41 @@ _dbus_read_credentials_socket  (int              handle,
 {
   int bytes_read = 0;
   DBusString buf;
-  
+
+  char *sid = NULL;
+  dbus_pid_t pid;
+  int retval = FALSE;
+
   // could fail due too OOM
-  if (_dbus_string_init(&buf))
+  if (_dbus_string_init (&buf))
     {
-      bytes_read = _dbus_read_socket(handle, &buf, 1 );
+      bytes_read = _dbus_read_socket (handle, &buf, 1 );
 
       if (bytes_read > 0) 
-        _dbus_verbose("got one zero byte from server");
+        _dbus_verbose ("got one zero byte from server\n");
+
+      _dbus_string_free (&buf);
+    }
+
+  pid = _dbus_get_peer_pid_from_tcp_handle (handle);
+  if (pid == 0)
+    return TRUE;
+
+  _dbus_credentials_add_pid (credentials, pid);
 
-      _dbus_string_free(&buf);
+  if (_dbus_getsid (&sid, pid))
+    {
+      if (!_dbus_credentials_add_windows_sid (credentials, sid))
+        goto out;
     }
 
-  _dbus_credentials_add_from_current_process (credentials);
-  _dbus_verbose("FIXME: get faked credentials from current process");
+  retval = TRUE;
 
-  return TRUE;
+out:
+  if (sid)
+    LocalFree (sid);
+
+  return retval;
 }
 
 /**
@@ -1761,11 +1969,8 @@ _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;
 }
 
@@ -1813,7 +2018,7 @@ _dbus_concat_dir_and_file (DBusString       *dir,
                             _dbus_string_get_length (dir));
 }
 
-/*---------------- DBusCredentials ----------------------------------
+/*---------------- DBusCredentials ----------------------------------*/
 
 /**
  * Adds the credentials corresponding to the given username.
@@ -1844,10 +2049,10 @@ _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
   dbus_bool_t retval = FALSE;
   char *sid = NULL;
 
-  if (!_dbus_getsid(&sid))
+  if (!_dbus_getsid(&sid, _dbus_getpid()))
     goto failed;
 
-  if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
+  if (!_dbus_credentials_add_pid (credentials, _dbus_getpid()))
     goto failed;
 
   if (!_dbus_credentials_add_windows_sid (credentials,sid))
@@ -1882,7 +2087,7 @@ _dbus_append_user_from_current_process (DBusString *str)
   dbus_bool_t retval = FALSE;
   char *sid = NULL;
 
-  if (!_dbus_getsid(&sid))
+  if (!_dbus_getsid(&sid, _dbus_getpid()))
     return FALSE;
 
   retval = _dbus_string_append (str,sid);
@@ -1895,7 +2100,7 @@ _dbus_append_user_from_current_process (DBusString *str)
  * Gets our process ID
  * @returns process ID
  */
-unsigned long
+dbus_pid_t
 _dbus_getpid (void)
 {
   return GetCurrentProcessId ();
@@ -1924,519 +2129,244 @@ _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;
+    *tv_usec = time64 % 1000000;
 }
 
-
 /**
- * signal (SIGPIPE, SIG_IGN);
+ * Get current time, as in gettimeofday(). Use the monotonic clock if
+ * available, to avoid problems when the system time changes.
+ *
+ * @param tv_sec return location for number of seconds
+ * @param tv_usec return location for number of microseconds
  */
 void
-_dbus_disable_sigpipe (void)
+_dbus_get_monotonic_time (long *tv_sec,
+                          long *tv_usec)
 {
+  /* no implementation yet, fall back to wall-clock time */
+  _dbus_get_real_time (tv_sec, tv_usec);
 }
 
-
-/* _dbus_read() is static on Windows, only used below in this file.
+/**
+ * signal (SIGPIPE, SIG_IGN);
  */
-static int
-_dbus_read (int               fd,
-            DBusString       *buffer,
-            int               count)
+void
+_dbus_disable_sigpipe (void)
 {
-  int bytes_read;
-  int start;
-  char *data;
-
-  _dbus_assert (count >= 0);
-
-  start = _dbus_string_get_length (buffer);
-
-  if (!_dbus_string_lengthen (buffer, count))
-    {
-      errno = ENOMEM;
-      return -1;
-    }
-
-  data = _dbus_string_get_data_len (buffer, start, count);
-
- again:
-
-  bytes_read = _read (fd, data, count);
-
-  if (bytes_read < 0)
-    {
-      if (errno == EINTR)
-        goto again;
-      else
-        {
-          /* put length back (note that this doesn't actually realloc anything) */
-          _dbus_string_set_length (buffer, start);
-          return -1;
-        }
-    }
-  else
-    {
-      /* put length back (doesn't actually realloc) */
-      _dbus_string_set_length (buffer, start + bytes_read);
-
-#if 0
-      if (bytes_read > 0)
-        _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
-#endif
-
-      return bytes_read;
-    }
 }
 
 /**
- * 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.
+ * Creates a directory; succeeds if the directory
+ * is created or already existed.
  *
- * @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 filename directory filename
+ * @param error initialized error object
+ * @returns #TRUE on success
  */
 dbus_bool_t
-_dbus_file_get_contents (DBusString       *str,
-                         const DBusString *filename,
-                         DBusError        *error)
-{
-  int fd;
-  struct _stati64 sb;
-  int orig_len;
-  int total;
+_dbus_create_directory (const DBusString *filename,
+                        DBusError        *error)
+{
   const char *filename_c;
 
   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
 
   filename_c = _dbus_string_get_const_data (filename);
 
-  fd = _open (filename_c, O_RDONLY | O_BINARY);
-  if (fd < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to open \"%s\": %s",
-                      filename_c,
-                      strerror (errno));
-      return FALSE;
-    }
-
-  _dbus_verbose ("file %s fd %d opened\n", filename_c, fd);
-
-  if (_fstati64 (fd, &sb) < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to stat \"%s\": %s",
-                      filename_c,
-                      strerror (errno));
-
-      _dbus_verbose ("fstat() failed: %s",
-                     strerror (errno));
-
-      _close (fd);
-
-      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);
-      _close (fd);
-      return FALSE;
-    }
-
-  total = 0;
-  orig_len = _dbus_string_get_length (str);
-  if (sb.st_size > 0 && S_ISREG (sb.st_mode))
+  if (!CreateDirectoryA (filename_c, NULL))
     {
-      int bytes_read;
-
-      while (total < (int) sb.st_size)
-        {
-          bytes_read = _dbus_read (fd, str, sb.st_size - total);
-          if (bytes_read <= 0)
-            {
-              dbus_set_error (error, _dbus_error_from_errno (errno),
-                              "Error reading \"%s\": %s",
-                              filename_c,
-                              strerror (errno));
-
-              _dbus_verbose ("read() failed: %s",
-                             strerror (errno));
-
-              _close (fd);
-              _dbus_string_set_length (str, orig_len);
-              return FALSE;
-            }
-          else
-            total += bytes_read;
-        }
+      if (GetLastError () == ERROR_ALREADY_EXISTS)
+        return TRUE;
 
-      _close (fd);
-      return TRUE;
-    }
-  else if (sb.st_size != 0)
-    {
-      _dbus_verbose ("Can only open regular files at the moment.\n");
       dbus_set_error (error, DBUS_ERROR_FAILED,
-                      "\"%s\" is not a regular file",
-                      filename_c);
-      _close (fd);
+                      "Failed to create directory %s: %s\n",
+                      filename_c, _dbus_strerror_from_errno ());
       return FALSE;
     }
   else
-    {
-      _close (fd);
-      return TRUE;
-    }
+    return TRUE;
 }
 
+
 /**
- * Writes a string out to a file. If the file exists,
- * it will be atomically overwritten by the new data.
+ * Generates the given number of random bytes,
+ * using the best mechanism we can come up with.
  *
- * @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
+ * @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_string_save_to_file (const DBusString *str,
-                           const DBusString *filename,
-                           DBusError        *error)
+_dbus_generate_random_bytes (DBusString *str,
+                             int         n_bytes)
 {
-  int fd;
-  int bytes_to_write;
-  const char *filename_c;
-  DBusString tmp_filename;
-  const char *tmp_filename_c;
-  int total;
-  const char *str_c;
-  dbus_bool_t need_unlink;
-  dbus_bool_t retval;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+  int old_len;
+  char *p;
+  HCRYPTPROV hprov;
 
-  fd = -1;
-  retval = FALSE;
-  need_unlink = FALSE;
+  old_len = _dbus_string_get_length (str);
 
-  if (!_dbus_string_init (&tmp_filename))
-    {
-      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
-      return FALSE;
-    }
+  if (!_dbus_string_lengthen (str, n_bytes))
+    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;
-    }
+  p = _dbus_string_get_data_len (str, old_len, n_bytes);
 
-  if (!_dbus_string_append (&tmp_filename, "."))
-    {
-      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
-      _dbus_string_free (&tmp_filename);
-      return FALSE;
-    }
+  if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
+    return FALSE;
 
-#define N_TMP_FILENAME_RANDOM_BYTES 8
-  if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
+  if (!CryptGenRandom (hprov, n_bytes, p))
     {
-      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
-      _dbus_string_free (&tmp_filename);
+      CryptReleaseContext (hprov, 0);
       return FALSE;
     }
 
-  filename_c = _dbus_string_get_const_data (filename);
-  tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
-
-  fd = _open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
-              0600);
-  if (fd < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Could not create %s: %s", tmp_filename_c,
-                      strerror (errno));
-      goto out;
-    }
-
-  _dbus_verbose ("tmp file %s fd %d opened\n", tmp_filename_c, fd);
+  CryptReleaseContext (hprov, 0);
 
-  need_unlink = TRUE;
+  return TRUE;
+}
 
-  total = 0;
-  bytes_to_write = _dbus_string_get_length (str);
-  str_c = _dbus_string_get_const_data (str);
+/**
+ * Gets the temporary files directory by inspecting the environment variables 
+ * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
+ *
+ * @returns location of temp directory
+ */
+const char*
+_dbus_get_tmpdir(void)
+{
+  static const char* tmpdir = NULL;
+  static char buf[1000];
 
-  while (total < bytes_to_write)
+  if (tmpdir == NULL)
     {
-      int bytes_written;
-
-      bytes_written = _write (fd, str_c + total, bytes_to_write - total);
+      char *last_slash;
 
-      if (bytes_written <= 0)
+      if (!GetTempPathA (sizeof (buf), buf))
         {
-          dbus_set_error (error, _dbus_error_from_errno (errno),
-                          "Could not write to %s: %s", tmp_filename_c,
-                          strerror (errno));
-          goto out;
+          _dbus_warn ("GetTempPath failed\n");
+          _dbus_abort ();
         }
 
-      total += bytes_written;
-    }
-
-  if (_close (fd) < 0)
-    {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Could not close file %s: %s",
-                      tmp_filename_c, strerror (errno));
-
-      goto out;
-    }
-
-  fd = -1;
-
-  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));
+      /* 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';
 
-      goto out;
+      tmpdir = buf;
     }
 
-  need_unlink = FALSE;
-
-  retval = TRUE;
-
- out:
-  /* close first, then unlink */
-
-  if (fd >= 0)
-    _close (fd);
-
-  if (need_unlink && _unlink (tmp_filename_c) < 0)
-    _dbus_verbose ("failed to unlink temp file %s: %s\n",
-                   tmp_filename_c, strerror (errno));
-
-  _dbus_string_free (&tmp_filename);
-
-  if (!retval)
-    _DBUS_ASSERT_ERROR_IS_SET (error);
+  _dbus_assert(tmpdir != NULL);
 
-  return retval;
+  return tmpdir;
 }
 
 
-/** Creates the given file, failing if the file already exists.
+/**
+ * Deletes the given file.
  *
  * @param filename the filename
  * @param error error location
- * @returns #TRUE if we created the file and it didn't exist
+ * 
+ * @returns #TRUE if unlink() succeeded
  */
 dbus_bool_t
-_dbus_create_file_exclusively (const DBusString *filename,
-                               DBusError        *error)
+_dbus_delete_file (const DBusString *filename,
+                   DBusError        *error)
 {
-  int fd;
   const char *filename_c;
 
   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
 
   filename_c = _dbus_string_get_const_data (filename);
 
-  fd = _open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
-              0600);
-  if (fd < 0)
+  if (DeleteFileA (filename_c) == 0)
     {
-      dbus_set_error (error,
-                      DBUS_ERROR_FAILED,
-                      "Could not create file %s: %s\n",
-                      filename_c,
-                      strerror (errno));
+      dbus_set_error (error, DBUS_ERROR_FAILED,
+                      "Failed to delete file %s: %s\n",
+                      filename_c, _dbus_strerror_from_errno ());
       return FALSE;
     }
+  else
+    return TRUE;
+}
 
-  _dbus_verbose ("exclusive file %s fd %d opened\n", filename_c, fd);
-
-  if (_close (fd) < 0)
-    {
-      dbus_set_error (error,
-                      DBUS_ERROR_FAILED,
-                      "Could not close file %s: %s\n",
-                      filename_c,
-                      strerror (errno));
-      return FALSE;
-    }
-
-  return TRUE;
-}
-
-
-/**
- * Creates a directory; succeeds if the directory
- * is created or already existed.
- *
- * @param filename directory filename
- * @param error initialized error object
- * @returns #TRUE on success
- */
-dbus_bool_t
-_dbus_create_directory (const DBusString *filename,
-                        DBusError        *error)
-{
-  const char *filename_c;
-
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
-
-  filename_c = _dbus_string_get_const_data (filename);
-
-  if (!CreateDirectory (filename_c, NULL))
-    {
-      if (GetLastError () == ERROR_ALREADY_EXISTS)
-        return TRUE;
-
-      dbus_set_error (error, DBUS_ERROR_FAILED,
-                      "Failed to create directory %s: %s\n",
-                      filename_c, strerror (errno));
-      return FALSE;
-    }
-  else
-    return TRUE;
-}
-
-
-/**
- * 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);
-
-  if (!_dbus_string_lengthen (str, n_bytes))
-    return FALSE;
-
-  p = _dbus_string_get_data_len (str, old_len, 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;
-}
-
-/**
- * Gets the temporary files directory by inspecting the environment variables 
- * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
+/*
+ * replaces the term DBUS_PREFIX in configure_time_path by the
+ * current dbus installation directory. On unix this function is a noop
  *
- * @returns location of temp directory
+ * @param configure_time_path
+ * @return real path
  */
-const char*
-_dbus_get_tmpdir(void)
+const char *
+_dbus_replace_install_prefix (const char *configure_time_path)
 {
-  static const char* tmpdir = NULL;
-
-  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";
-    }
-
-  _dbus_assert(tmpdir != NULL);
-
-  return tmpdir;
-}
+#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;
 
-/**
- * Deletes the given file.
- *
- * @param filename the filename
- * @param error error location
- * 
- * @returns #TRUE if unlink() succeeded
- */
-dbus_bool_t
-_dbus_delete_file (const DBusString *filename,
-                   DBusError        *error)
-{
-  const char *filename_c;
+  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;
+  }
 
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+  strcpy (retval, runtime_prefix);
+  strcat (retval, configure_time_path + strlen (DBUS_PREFIX) + 1);
 
-  filename_c = _dbus_string_get_const_data (filename);
+  /* 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.
+   */
 
-  if (_unlink (filename_c) < 0)
-    {
-      dbus_set_error (error, DBUS_ERROR_FAILED,
-                      "Failed to delete file %s: %s\n",
-                      filename_c, strerror (errno));
-      return FALSE;
-    }
-  else
-    return TRUE;
+  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
@@ -2497,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
@@ -2505,6 +2445,7 @@ static PVOID  (WINAPI *pSymFunctionTableAccess)(
   HANDLE hProcess,
   DWORD AddrBase
 );
+#endif
 static BOOL  (WINAPI *pSymInitialize)(
   HANDLE hProcess,
   PSTR UserSearchPath,
@@ -2559,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
@@ -2567,6 +2518,7 @@ PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
   HANDLE hProcess,
   DWORD AddrBase
 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
+#endif
     pSymInitialize = (BOOL  (WINAPI *)(
   HANDLE hProcess,
   PSTR UserSearchPath,
@@ -2632,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
@@ -2690,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();
@@ -2791,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;
@@ -2822,76 +2795,203 @@ 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";
 // mutex to determine if dbus-daemon is already started (per user)
 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
 // named shm for dbus adress info (per user)
-#ifdef _DEBUG
-static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
-#else
 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
-#endif
 
-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;
-  char *adr = NULL;
-  char szUserName[64];
-  DWORD dwUserNameSize = sizeof(szUserName);
-  char szDBusDaemonMutex[128];
-  char szDBusDaemonAddressInfo[128];
-  char szAddress[128];
-  DWORD ret;
-
-  _dbus_assert(host);
-  _dbus_assert(port);
-
-  _snprintf(szAddress, sizeof(szAddress) - 1, "tcp:host=%s,port=%d", host, port);
-  ret = GetUserName(szUserName, &dwUserNameSize);
-  _dbus_assert(ret != 0);
-  _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
-            cDBusDaemonMutex, szUserName);
-  _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
-            cDBusDaemonAddressInfo, szUserName);
-
-  // before _dbus_global_lock to keep correct lock/release order
-  hDBusDaemonMutex = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
-  ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
-  if ( ret != WAIT_OBJECT_0 ) {
-    _dbus_warn("Could not lock mutex %s (return code %d). daemon already running?\n", szDBusDaemonMutex, ret );
-    _dbus_assert( !"Could not lock mutex, daemon already running?" );
-  }
+  DBusString mutex_name;
+
+  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
+  if (hDBusDaemonMutex)
+      return TRUE;
+
+  // 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 );
+
+  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_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;
+
+  _dbus_assert (address);
+
+  if (!_dbus_get_mutex_name(&mutex_name,scope))
+    {
+      _dbus_string_free( &mutex_name );
+      return FALSE;
+    }
+
+  // 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 );
@@ -2908,24 +3008,16 @@ _dbus_daemon_release()
 }
 
 static dbus_bool_t
-_dbus_get_autolaunch_shm(DBusString *adress)
+_dbus_get_autolaunch_shm (DBusString *address, DBusString *shm_name)
 {
   HANDLE sharedMem;
-  char *adr;
-  char szUserName[64];
-  DWORD dwUserNameSize = sizeof(szUserName);
-  char szDBusDaemonAddressInfo[128];
+  char *shared_addr;
   int i;
 
-  if( !GetUserName(szUserName, &dwUserNameSize) )
-      return FALSE;
-  _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
-            cDBusDaemonAddressInfo, szUserName);
-
   // read shm
   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 );
       if ( sharedMem != 0)
@@ -2935,17 +3027,17 @@ _dbus_get_autolaunch_shm(DBusString *adress)
   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 );
 
@@ -2953,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;
@@ -3003,31 +3096,63 @@ _dbus_get_autolaunch_address (DBusString *address,
   LPSTR lpFile;
   char dbus_exe_path[MAX_PATH];
   char dbus_args[MAX_PATH * 2];
-#ifdef _DEBUG
-  const char * daemon_name = "dbus-daemond.exe";
-#else
-  const char * daemon_name = "dbus-daemon.exe";
-#endif
-
-  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_verbose("found already running dbus daemon\n");
+        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))
+    {
+        _dbus_verbose( "found running dbus daemon at %s\n",
+                       _dbus_string_get_const_data (&shm_name) );
         retval = TRUE;
         goto out;
     }
 
   if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
     {
-      printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
-      printf ("or start the daemon manually\n\n");
-      printf ("");
-      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);
@@ -3039,12 +3164,17 @@ _dbus_get_autolaunch_address (DBusString *address,
 //  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 = _dbus_get_autolaunch_shm( address );
+      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;
     }
-  
-  if (retval == FALSE)
-    dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
 
 out:
   if (retval)
@@ -3072,6 +3202,21 @@ _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_SYSTEM_SERVICEDIR "/dbus-1/system-services"
@@ -3086,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 
@@ -3101,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");
 
@@ -3153,8 +3336,6 @@ _dbus_get_standard_system_servicedirs (DBusList **dirs)
   return TRUE;
 }
 
-_DBUS_DEFINE_GLOBAL_LOCK (atomic);
-
 /**
  * Atomically increments an integer
  *
@@ -3185,7 +3366,30 @@ _dbus_atomic_dec (DBusAtomic *atomic)
   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
@@ -3197,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;
 }
 
 /**
@@ -3214,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;
+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;
     }
-  else
-    {
-      *s = '\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;
 }
 
 /** 
@@ -3252,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
@@ -3263,12 +3476,11 @@ _dbus_get_config_file_name(DBusString *config_file, char *s)
 {
   char path[MAX_PATH*2];
   int path_size = sizeof(path);
-  int len = 4 + strlen(s);
 
   if (!_dbus_get_install_root(path,path_size))
     return FALSE;
 
-  if(len > sizeof(path)-2)
+  if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
     return FALSE;
   strcat(path,"etc\\");
   strcat(path,s);
@@ -3282,9 +3494,9 @@ _dbus_get_config_file_name(DBusString *config_file, char *s)
     {
       if (!_dbus_get_install_root(path,path_size))
         return FALSE;
-      if(len + strlen(path) > sizeof(path)-2)
+      if(strlen(s) + 11 + strlen(path) > sizeof(path)-2)
         return FALSE;
-      strcat(path,"bus\\");
+      strcat(path,"etc\\dbus-1\\");
       strcat(path,s);
   
       if (_dbus_file_exists(path)) 
@@ -3292,6 +3504,21 @@ _dbus_get_config_file_name(DBusString *config_file, char *s)
           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;
 }    
@@ -3352,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));
@@ -3361,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;
     
@@ -3393,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;
@@ -3411,6 +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 */