[daemon-fix] Fixed sending daemon match rules for kdbus broadcasts
[platform/upstream/dbus.git] / dbus / dbus-sysdeps-util-win.c
index e4a30ba..4678b11 100644 (file)
  * 
  * 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
  *
  */
 
-#undef open
+#include <config.h>
 
 #define STRSAFE_NO_DEPRECATE
 
 #include "dbus-string.h"
 #include "dbus-sysdeps.h"
 #include "dbus-sysdeps-win.h"
+#include "dbus-sockets-win.h"
 #include "dbus-memory.h"
-
-#include <io.h>
-#include <sys/stat.h>
-#include <aclapi.h>
+#include "dbus-pipe.h"
 
 #include <stdio.h>
 #include <stdlib.h>
-#include <fcntl.h>
+#if HAVE_ERRNO_H
 #include <errno.h>
+#endif
+#include <winsock2.h>   // WSA error codes
 
-#if defined __MINGW32__ || (defined _MSC_VER && _MSC_VER <= 1310)
-/* save string functions version
-   using DBusString needs to much time because of uncommon api 
-*/ 
-#define errno_t int
-
-errno_t strcat_s(char *dest, size_t size, char *src) 
-{
-  _dbus_assert(strlen(dest) + strlen(src) +1 <= size);
-  strcat(dest,src);
-  return 0;
-}
-
-errno_t strcpy_s(char *dest, size_t size, char *src)
-{
-  _dbus_assert(strlen(src) +1 <= size);
-  strcpy(dest,src);  
-  return 0;
-}
+#ifndef DBUS_WINCE
+#include <io.h>
+#include <lm.h>
+#include <sys/stat.h>
 #endif
 
+
 /**
  * Does the chdir, fork, setsid, etc. to become a daemon process.
  *
  * @param pidfile #NULL, or pidfile to create
- * @param print_pid_fd file descriptor to print daemon's pid to, or -1 for none
+ * @param print_pid_pipe file descriptor to print daemon's pid to, or -1 for none
  * @param error return location for errors
+ * @param keep_umask #TRUE to keep the original umask
  * @returns #FALSE on failure
  */
 dbus_bool_t
 _dbus_become_daemon (const DBusString *pidfile,
                      DBusPipe         *print_pid_pipe,
-                     DBusError        *error)
+                     DBusError        *error,
+                     dbus_bool_t       keep_umask)
 {
-  return TRUE;
+  dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
+                  "Cannot daemonize on Windows");
+  return FALSE;
 }
 
 /**
@@ -88,48 +78,76 @@ _dbus_become_daemon (const DBusString *pidfile,
  * @param error return location for errors
  * @returns #FALSE on failure
  */
-dbus_bool_t
+static dbus_bool_t
 _dbus_write_pid_file (const DBusString *filename,
                       unsigned long     pid,
                       DBusError        *error)
 {
   const char *cfilename;
-  DBusFile file;
-  FILE *f;
+  HANDLE hnd;
+  char pidstr[20];
+  int total;
+  int bytes_to_write;
+
+  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
 
   cfilename = _dbus_string_get_const_data (filename);
 
-  if (!_dbus_file_open(&file, cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644))
+  hnd = CreateFileA (cfilename, GENERIC_WRITE,
+                     FILE_SHARE_READ | FILE_SHARE_WRITE,
+                     NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL,
+                     INVALID_HANDLE_VALUE);
+  if (hnd == INVALID_HANDLE_VALUE)
     {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to open \"%s\": %s", cfilename,
-                      _dbus_strerror (errno));
+      char *emsg = _dbus_win_error_string (GetLastError ());
+      dbus_set_error (error, _dbus_win_error_from_last_error (),
+                      "Could not create PID file %s: %s",
+                      cfilename, emsg);
+      _dbus_win_free_error_string (emsg);
       return FALSE;
     }
 
-  if ((f = fdopen (file.FDATA, "w")) == NULL)
+  if (snprintf (pidstr, sizeof (pidstr), "%lu\n", pid) < 0)
     {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to fdopen fd %d: %s", file.FDATA, _dbus_strerror (errno));
-      _dbus_file_close (&file, NULL);
+      dbus_set_error (error, _dbus_error_from_system_errno (),
+                      "Failed to format PID for \"%s\": %s", cfilename,
+                      _dbus_strerror_from_errno ());
+      CloseHandle (hnd);
       return FALSE;
     }
 
-  if (fprintf (f, "%lu\n", pid) < 0)
+  total = 0;
+  bytes_to_write = strlen (pidstr);;
+
+  while (total < bytes_to_write)
     {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to write to \"%s\": %s", cfilename,
-                      _dbus_strerror (errno));
+      DWORD bytes_written;
+      BOOL res;
 
-      fclose (f);
-      return FALSE;
+      res = WriteFile (hnd, pidstr + total, bytes_to_write - total,
+                       &bytes_written, NULL);
+
+      if (res == 0 || bytes_written <= 0)
+        {
+          char *emsg = _dbus_win_error_string (GetLastError ());
+          dbus_set_error (error, _dbus_win_error_from_last_error (),
+                           "Could not write to %s: %s", cfilename, emsg);
+          _dbus_win_free_error_string (emsg);
+          CloseHandle (hnd);
+          return FALSE;
+        }
+
+      total += bytes_written;
     }
 
-  if (fclose (f) == EOF)
+  if (CloseHandle (hnd) == 0)
     {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
-                      "Failed to close \"%s\": %s", cfilename,
-                      _dbus_strerror (errno));
+      char *emsg = _dbus_win_error_string (GetLastError ());
+      dbus_set_error (error, _dbus_win_error_from_last_error (),
+                       "Could not close file %s: %s",
+                      cfilename, emsg);
+      _dbus_win_free_error_string (emsg);
+
       return FALSE;
     }
 
@@ -137,6 +155,84 @@ _dbus_write_pid_file (const DBusString *filename,
 }
 
 /**
+ * Writes the given pid_to_write to a pidfile (if non-NULL) and/or to a
+ * pipe (if non-NULL). Does nothing if pidfile and print_pid_pipe are both
+ * NULL.
+ *
+ * @param pidfile the file to write to or #NULL
+ * @param print_pid_pipe the pipe to write to or #NULL
+ * @param pid_to_write the pid to write out
+ * @param error error on failure
+ * @returns FALSE if error is set
+ */
+dbus_bool_t
+_dbus_write_pid_to_file_and_pipe (const DBusString *pidfile,
+                                  DBusPipe         *print_pid_pipe,
+                                  dbus_pid_t        pid_to_write,
+                                  DBusError        *error)
+{
+  if (pidfile)
+    {
+      _dbus_verbose ("writing pid file %s\n", _dbus_string_get_const_data (pidfile));
+      if (!_dbus_write_pid_file (pidfile,
+                                 pid_to_write,
+                                 error))
+        {
+          _dbus_verbose ("pid file write failed\n");
+          _DBUS_ASSERT_ERROR_IS_SET(error);
+          return FALSE;
+        }
+    }
+  else
+    {
+      _dbus_verbose ("No pid file requested\n");
+    }
+
+  if (print_pid_pipe != NULL && _dbus_pipe_is_valid (print_pid_pipe))
+    {
+      DBusString pid;
+      int bytes;
+
+      _dbus_verbose ("writing our pid to pipe %d\n", print_pid_pipe->fd);
+
+      if (!_dbus_string_init (&pid))
+        {
+          _DBUS_SET_OOM (error);
+          return FALSE;
+        }
+
+      if (!_dbus_string_append_int (&pid, pid_to_write) ||
+          !_dbus_string_append (&pid, "\n"))
+        {
+          _dbus_string_free (&pid);
+          _DBUS_SET_OOM (error);
+          return FALSE;
+        }
+
+      bytes = _dbus_string_get_length (&pid);
+      if (_dbus_pipe_write (print_pid_pipe, &pid, 0, bytes, error) != bytes)
+        {
+          /* _dbus_pipe_write sets error only on failure, not short write */
+          if (error != NULL && !dbus_error_is_set(error))
+            {
+              dbus_set_error (error, DBUS_ERROR_FAILED,
+                              "Printing message bus PID: did not write enough bytes\n");
+            }
+          _dbus_string_free (&pid);
+          return FALSE;
+        }
+
+      _dbus_string_free (&pid);
+    }
+  else
+    {
+      _dbus_verbose ("No pid pipe to write to\n");
+    }
+
+  return TRUE;
+}
+
+/**
  * Verify that after the fork we can successfully change to this user.
  *
  * @param user the username given in the daemon configuration
@@ -162,134 +258,64 @@ _dbus_change_to_daemon_user  (const char    *user,
   return TRUE;
 }
 
-/**
- * Changes the user and group the bus is running as.
- *
- * @param uid the new user ID
- * @param gid the new group ID
- * @param error return location for errors
- * @returns #FALSE on failure
- */
-dbus_bool_t
-_dbus_change_identity  (dbus_uid_t     uid,
-                        dbus_gid_t     gid,
-                        DBusError     *error)
+void
+_dbus_request_file_descriptor_limit (unsigned int limit)
 {
-  return TRUE;
 }
 
-/** Checks if user is at the console
-*
-* @param username user to check
-* @param error return location for errors
-* @returns #TRUE is the user is at the consolei and there are no errors
-*/
-dbus_bool_t
-_dbus_user_at_console(const char *username,
-                      DBusError  *error)
+void
+_dbus_init_system_log (dbus_bool_t is_daemon)
 {
-#ifdef DBUS_WINCE
-       return TRUE;
-#else
-  dbus_bool_t retval = FALSE;
-  wchar_t *wusername;
-  DWORD sid_length;
-  PSID user_sid, console_user_sid;
-  HWINSTA winsta;
-
-  wusername = _dbus_win_utf8_to_utf16 (username, error);
-  if (!wusername)
-    return FALSE;
-
-  // TODO remove
-  if (!_dbus_win_account_to_sid (wusername, &user_sid, error))
-    goto out0;
-
-  /* Now we have the SID for username. Get the SID of the
-   * user at the "console" (window station WinSta0)
-   */
-  if (!(winsta = OpenWindowStation ("WinSta0", FALSE, READ_CONTROL)))
-    {
-      _dbus_win_set_error_from_win_error (error, GetLastError ());
-      goto out2;
-    }
-
-  sid_length = 0;
-  GetUserObjectInformation (winsta, UOI_USER_SID,
-                            NULL, 0, &sid_length);
-  if (sid_length == 0)
-    {
-      /* Nobody is logged on */
-      goto out2;
-    }
-
-  if (sid_length < 0 || sid_length > 1000)
-    {
-      dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID length");
-      goto out3;
-    }
-
-  console_user_sid = dbus_malloc (sid_length);
-  if (!console_user_sid)
-    {
-      _DBUS_SET_OOM (error);
-      goto out3;
-    }
-
-  if (!GetUserObjectInformation (winsta, UOI_USER_SID,
-                                 console_user_sid, sid_length, &sid_length))
-    {
-      _dbus_win_set_error_from_win_error (error, GetLastError ());
-      goto out4;
-    }
-
-  if (!IsValidSid (console_user_sid))
-    {
-      dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
-      goto out4;
-    }
-
-  retval = EqualSid (user_sid, console_user_sid);
-
-out4:
-  dbus_free (console_user_sid);
-out3:
-  CloseWindowStation (winsta);
-out2:
-  dbus_free (user_sid);
-out0:
-  dbus_free (wusername);
-
-  return retval;
-#endif //DBUS_WINCE
+  /* OutputDebugStringA doesn't need any special initialization, do nothing */
 }
 
 /**
- * Removes a directory; Directory must be empty
- * 
- * @param filename directory filename
- * @param error initialized error object
- * @returns #TRUE on success
+ * Log a message to the system log file (e.g. syslog on Unix).
+ *
+ * @param severity a severity value
+ * @param msg a printf-style format string
  */
-dbus_bool_t
-_dbus_delete_directory (const DBusString *filename,
-                        DBusError        *error)
+void
+_dbus_system_log (DBusSystemLogSeverity severity, const char *msg, ...)
 {
-  const char *filename_c;
+  va_list args;
 
-  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+  va_start (args, msg);
 
-  filename_c = _dbus_string_get_const_data (filename);
+  _dbus_system_logv (severity, msg, args);
 
-  if (rmdir (filename_c) != 0)
-    {
-      dbus_set_error (error, DBUS_ERROR_FAILED,
-                      "Failed to remove directory %s: %s\n",
-                      filename_c, _dbus_strerror (errno));
-      return FALSE;
-    }
+  va_end (args);
+}
 
-  return TRUE;
+/**
+ * Log a message to the system log file (e.g. syslog on Unix).
+ *
+ * @param severity a severity value
+ * @param msg a printf-style format string
+ * @param args arguments for the format string
+ *
+ * If the FATAL severity is given, this function will terminate the program
+ * with an error code.
+ */
+void
+_dbus_system_logv (DBusSystemLogSeverity severity, const char *msg, va_list args)
+{
+  char *s = "";
+  char buf[1024];
+  
+  switch(severity) 
+   {
+     case DBUS_SYSTEM_LOG_INFO: s = "info"; break;
+     case DBUS_SYSTEM_LOG_SECURITY: s = "security"; break;
+     case DBUS_SYSTEM_LOG_FATAL: s = "fatal"; break;
+   }
+   
+  sprintf(buf,"%s%s",s,msg);
+  vsprintf(buf,buf,args);
+  OutputDebugStringA(buf);
+  
+  if (severity == DBUS_SYSTEM_LOG_FATAL)
+    exit (1);
 }
 
 /** Installs a signal handler
@@ -304,34 +330,6 @@ _dbus_set_signal_handler (int               sig,
   _dbus_verbose ("_dbus_set_signal_handler() has to be implemented\n");
 }
 
-/** 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)
-{
-  HANDLE h = CreateFile(
-          file, /* LPCTSTR lpFileName*/
-          0, /* DWORD dwDesiredAccess */
-          0, /* DWORD dwShareMode*/
-          NULL, /* LPSECURITY_ATTRIBUTES lpSecurityAttributes */
-          OPEN_EXISTING, /* DWORD dwCreationDisposition */
-          FILE_ATTRIBUTE_NORMAL, /* DWORD dwFlagsAndAttributes */
-          NULL /* HANDLE hTemplateFile */
-        );
-
-    /* file not found, use local copy of session.conf  */
-    if (h != INVALID_HANDLE_VALUE && GetLastError() != ERROR_PATH_NOT_FOUND)
-      {
-        CloseHandle(h);
-        return TRUE;
-      }
-    else
-        return FALSE;  
-}
-
 /**
  * stat() wrapper.
  *
@@ -345,28 +343,16 @@ _dbus_stat(const DBusString *filename,
            DBusStat         *statbuf,
            DBusError        *error)
 {
-#ifdef DBUS_WINCE
-       return TRUE;
-       //TODO
-#else
   const char *filename_c;
-#if !defined(DBUS_WIN) && !defined(DBUS_WINCE)
-
-  struct stat sb;
-#else
-
   WIN32_FILE_ATTRIBUTE_DATA wfad;
   char *lastdot;
   DWORD rc;
-  PSID owner_sid, group_sid;
-  PSECURITY_DESCRIPTOR sd;
-#endif
 
   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
 
   filename_c = _dbus_string_get_const_data (filename);
 
-  if (!GetFileAttributesEx (filename_c, GetFileExInfoStandard, &wfad))
+  if (!GetFileAttributesExA (filename_c, GetFileExInfoStandard, &wfad))
     {
       _dbus_win_set_error_from_win_error (error, GetLastError ());
       return FALSE;
@@ -390,28 +376,36 @@ _dbus_stat(const DBusString *filename,
 
   statbuf->nlink = 1;
 
-  sd = NULL;
-  rc = GetNamedSecurityInfo ((char *) filename_c, SE_FILE_OBJECT,
-                             OWNER_SECURITY_INFORMATION |
-                             GROUP_SECURITY_INFORMATION,
-                             &owner_sid, &group_sid,
-                             NULL, NULL,
-                             &sd);
-  if (rc != ERROR_SUCCESS)
-    {
-      _dbus_win_set_error_from_win_error (error, rc);
-      if (sd != NULL)
-        LocalFree (sd);
-      return FALSE;
-    }
-
 #ifdef ENABLE_UID_TO_SID
-  /* FIXME */
-  statbuf->uid = _dbus_win_sid_to_uid_t (owner_sid);
-  statbuf->gid = _dbus_win_sid_to_uid_t (group_sid);
-#endif
+  {
+    PSID owner_sid, group_sid;
+    PSECURITY_DESCRIPTOR sd;
+
+    sd = NULL;
+    rc = GetNamedSecurityInfo ((char *) filename_c, SE_FILE_OBJECT,
+                               OWNER_SECURITY_INFORMATION |
+                               GROUP_SECURITY_INFORMATION,
+                               &owner_sid, &group_sid,
+                               NULL, NULL,
+                               &sd);
+    if (rc != ERROR_SUCCESS)
+      {
+        _dbus_win_set_error_from_win_error (error, rc);
+        if (sd != NULL)
+          LocalFree (sd);
+        return FALSE;
+      }
+    
+    /* FIXME */
+    statbuf->uid = _dbus_win_sid_to_uid_t (owner_sid);
+    statbuf->gid = _dbus_win_sid_to_uid_t (group_sid);
 
-  LocalFree (sd);
+    LocalFree (sd);
+  }
+#else
+  statbuf->uid = DBUS_UID_UNSET;
+  statbuf->gid = DBUS_GID_UNSET;
+#endif
 
   statbuf->size = ((dbus_int64_t) wfad.nFileSizeHigh << 32) + wfad.nFileSizeLow;
 
@@ -428,27 +422,9 @@ _dbus_stat(const DBusString *filename,
      wfad.ftCreationTime.dwLowDateTime) / 10000000 - DBUS_INT64_CONSTANT (116444736000000000);
 
   return TRUE;
-#endif //DBUS_WINCE
 }
 
 
-#ifdef HAVE_DIRENT_H
-
-// mingw ships with dirent.h
-#include <dirent.h>
-#define _dbus_opendir opendir
-#define _dbus_readdir readdir
-#define _dbus_closedir closedir
-
-#else
-
-#ifdef HAVE_IO_H
-#include <io.h> // win32 file functions
-#endif
-
-#include <sys/types.h>
-#include <stdlib.h>
-
 /* This file is part of the KDE project
 Copyright (C) 2000 Werner Almesberger
 
@@ -488,10 +464,10 @@ struct dirent
 /* typedef DIR - not the same as Unix */
 typedef struct
   {
-    long handle;                /* _findfirst/_findnext handle */
-    short offset;                /* offset into directory */
+    HANDLE handle;              /* FindFirst/FindNext handle */
+    short offset;               /* offset into directory */
     short finished;             /* 1 if there are not more files */
-    struct _finddata_t fileinfo;  /* from _findfirst/_findnext */
+    WIN32_FIND_DATAA fileinfo;  /* from FindFirst/FindNext */
     char *dir;                  /* the dir we are reading */
     struct dirent dent;         /* the dirent to return */
   }
@@ -507,14 +483,16 @@ DIR;
 * The dirent struct is compatible with Unix, except that d_ino is
 * always 1 and d_off is made up as we go along.
 *
+* Error codes are not available with errno but GetLastError.
+*
 * The DIR typedef is not compatible with Unix.
 **********************************************************************/
 
-DIR * _dbus_opendir(const char *dir)
+static DIR * _dbus_opendir(const char *dir)
 {
   DIR *dp;
   char *filespec;
-  long handle;
+  HANDLE handle;
   int index;
 
   filespec = malloc(strlen(dir) + 2 + 1);
@@ -529,9 +507,10 @@ DIR * _dbus_opendir(const char *dir)
   dp->finished = 0;
   dp->dir = strdup(dir);
 
-  if ((handle = _findfirst(filespec, &(dp->fileinfo))) < 0)
+  handle = FindFirstFileA(filespec, &(dp->fileinfo));
+  if (handle == INVALID_HANDLE_VALUE)
     {
-      if (errno == ENOENT)
+      if (GetLastError() == ERROR_NO_MORE_FILES)
         dp->finished = 1;
       else
         return NULL;
@@ -543,36 +522,41 @@ DIR * _dbus_opendir(const char *dir)
   return dp;
 }
 
-struct dirent * _dbus_readdir(DIR *dp)
-  {
-    if (!dp || dp->finished)
-      return NULL;
-
-    if (dp->offset != 0)
-      {
-        if (_findnext(dp->handle, &(dp->fileinfo)) < 0)
-          {
-            dp->finished = 1;
-            errno = 0;
-            return NULL;
-          }
-      }
-    dp->offset++;
+static struct dirent * _dbus_readdir(DIR *dp)
+{
+  int saved_err = GetLastError();
 
-    strncpy(dp->dent.d_name, dp->fileinfo.name, _MAX_FNAME);
-    dp->dent.d_ino = 1;
-    dp->dent.d_reclen = strlen(dp->dent.d_name);
-    dp->dent.d_off = dp->offset;
+  if (!dp || dp->finished)
+    return NULL;
 
-    return &(dp->dent);
-  }
+  if (dp->offset != 0)
+    {
+      if (FindNextFileA(dp->handle, &(dp->fileinfo)) == 0)
+        {
+          if (GetLastError() == ERROR_NO_MORE_FILES)
+            {
+              SetLastError(saved_err);
+              dp->finished = 1;
+            }
+          return NULL;
+        }
+    }
+  dp->offset++;
+  
+  strncpy(dp->dent.d_name, dp->fileinfo.cFileName, _MAX_FNAME);
+  dp->dent.d_ino = 1;
+  dp->dent.d_reclen = strlen(dp->dent.d_name);
+  dp->dent.d_off = dp->offset;
+  
+  return &(dp->dent);
+}
 
 
-int _dbus_closedir(DIR *dp)
+static int _dbus_closedir(DIR *dp)
 {
   if (!dp)
     return 0;
-  _findclose(dp->handle);
+  FindClose(dp->handle);
   if (dp->dir)
     free(dp->dir);
   if (dp)
@@ -581,7 +565,6 @@ int _dbus_closedir(DIR *dp)
   return 0;
 }
 
-#endif //#ifdef HAVE_DIRENT_H
 
 /**
  * Internals of directory iterator
@@ -614,10 +597,11 @@ _dbus_directory_open (const DBusString *filename,
   d = _dbus_opendir (filename_c);
   if (d == NULL)
     {
-      dbus_set_error (error, _dbus_error_from_errno (errno),
+      char *emsg = _dbus_win_error_string (GetLastError ());
+      dbus_set_error (error, _dbus_win_error_from_last_error (),
                       "Failed to read directory \"%s\": %s",
-                      filename_c,
-                      _dbus_strerror (errno));
+                      filename_c, emsg);
+      _dbus_win_free_error_string (emsg);
       return NULL;
     }
   iter = dbus_new0 (DBusDirIter, 1);
@@ -657,14 +641,17 @@ _dbus_directory_get_next_file (DBusDirIter      *iter,
   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
 
 again:
-  errno = 0;
+  SetLastError (0);
   ent = _dbus_readdir (iter->d);
   if (ent == NULL)
     {
-      if (errno != 0)
-        dbus_set_error (error,
-                        _dbus_error_from_errno (errno),
-                        "%s", _dbus_strerror (errno));
+      if (GetLastError() != 0)
+        {
+          char *emsg = _dbus_win_error_string (GetLastError ());
+          dbus_set_error (error, _dbus_win_error_from_last_error (),
+                          "Failed to get next in directory: %s", emsg);
+          _dbus_win_free_error_string (emsg);
+        }
       return FALSE;
     }
   else if (ent->d_name[0] == '.' &&
@@ -695,23 +682,6 @@ _dbus_directory_close (DBusDirIter *iter)
   dbus_free (iter);
 }
 
-/**
- * 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;
-}
-
 /** @} */ /* End of DBusInternalsUtils functions */
 
 /**
@@ -799,6 +769,11 @@ _dbus_unix_user_is_process_owner (dbus_uid_t uid)
   return FALSE;
 }
 
+dbus_bool_t _dbus_windows_user_is_process_owner (const char *windows_sid)
+{
+  return TRUE;
+}
+
 /*=====================================================================
   unix emulation functions - should be removed sometime in the future
  =====================================================================*/
@@ -816,6 +791,8 @@ dbus_bool_t
 _dbus_unix_user_is_at_console (dbus_uid_t         uid,
                                DBusError         *error)
 {
+  dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
+                  "UNIX user IDs not supported on Windows\n");
   return FALSE;
 }
 
@@ -880,187 +857,6 @@ _dbus_unix_groups_from_uid (dbus_uid_t            uid,
  ************************************************************************/
 
 
-/**
- * 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
-}
 
 
 
@@ -1710,3 +1506,231 @@ _dbus_lm_strerror(int error_number)
   return msg;
 #endif //DBUS_WINCE
 }
+
+/**
+ * Get a printable string describing the command used to execute
+ * the process with pid.  This string should only be used for
+ * informative purposes such as logging; it may not be trusted.
+ *
+ * The command is guaranteed to be printable ASCII and no longer
+ * than max_len.
+ *
+ * @param pid Process id
+ * @param str Append command to this string
+ * @param max_len Maximum length of returned command
+ * @param error return location for errors
+ * @returns #FALSE on error
+ */
+dbus_bool_t
+_dbus_command_for_pid (unsigned long  pid,
+                       DBusString    *str,
+                       int            max_len,
+                       DBusError     *error)
+{
+  // FIXME
+  return FALSE;
+}
+
+/*
+ * replaces the term DBUS_PREFIX in configure_time_path by the
+ * current dbus installation directory. On unix this function is a noop
+ *
+ * @param configure_time_path
+ * @return real path
+ */
+const char *
+_dbus_replace_install_prefix (const char *configure_time_path)
+{
+#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
+}
+
+/**
+ * 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"
+
+/**
+ * Returns the standard directories for a session bus to look for service
+ * activation files
+ *
+ * On Windows this should be data directories:
+ *
+ * %CommonProgramFiles%/dbus
+ *
+ * and
+ *
+ * relocated DBUS_DATADIR
+ *
+ * @param dirs the directory list we are returning
+ * @returns #FALSE on OOM
+ */
+
+dbus_bool_t
+_dbus_get_standard_session_servicedirs (DBusList **dirs)
+{
+  const char *common_progs;
+  DBusString servicedir_path;
+
+  if (!_dbus_string_init (&servicedir_path))
+    return FALSE;
+
+#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");
+
+  if (common_progs != NULL)
+    {
+      if (!_dbus_string_append (&servicedir_path, common_progs))
+        goto oom;
+
+      if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
+        goto oom;
+    }
+
+  if (!_dbus_split_paths_and_append (&servicedir_path,
+                               DBUS_STANDARD_SESSION_SERVICEDIR,
+                               dirs))
+    goto oom;
+
+  _dbus_string_free (&servicedir_path);
+  return TRUE;
+
+ oom:
+  _dbus_string_free (&servicedir_path);
+  return FALSE;
+}
+
+/**
+ * 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;
+}
+
+/**
+ * Append the absolute path of the system.conf file
+ * (there is no system bus on Windows so this can just
+ * return FALSE and print a warning or something)
+ *
+ * @param str the string to append to
+ * @returns #FALSE if no memory
+ */
+dbus_bool_t
+_dbus_append_system_config_file (DBusString *str)
+{
+  return _dbus_get_config_file_name(str, "system.conf");
+}
+
+/**
+ * Append the absolute path of the session.conf file.
+ *
+ * @param str the string to append to
+ * @returns #FALSE if no memory
+ */
+dbus_bool_t
+_dbus_append_session_config_file (DBusString *str)
+{
+  return _dbus_get_config_file_name(str, "session.conf");
+}