]> git.sur5r.net Git - bacula/bacula/blobdiff - bacula/src/win32/compat/compat.cpp
This commit was manufactured by cvs2svn to create tag
[bacula/bacula] / bacula / src / win32 / compat / compat.cpp
index ebdf82ba8244aac5c48c3208f159273b445a9630..80a77f578d8152f78a349974c01b3064d599c5dd 100644 (file)
@@ -1,9 +1,12 @@
-//                              -*- Mode: C++ -*- 
+//                              -*- Mode: C++ -*-
 // compat.cpp -- compatibilty layer to make bacula-fd run
 //               natively under windows
 //
-// Copyright (C)2004 Raider Solutions, Inc
-// 
+// Copyright transferred from Raider Solutions, Inc to
+//   Kern Sibbald and John Walker by express permission.
+//
+// Copyright (C) 2004 Kern Sibbald and John Walker
+//
 //   This program is free software; you can redistribute it and/or
 //   modify it under the terms of the GNU General Public License as
 //   published by the Free Software Foundation; either version 2 of
@@ -21,9 +24,6 @@
 //
 // Author          : Christopher S. Hull
 // Created On      : Sat Jan 31 15:55:00 2004
-// Last Modified By: Christopher S. Hull
-// Last Modified On: Mon Feb  9 17:22:31 2004
-// Update Count    : 591
 // $Id$
 
 #include <stdio.h>
 #include "compat.h"
 #include "pthread.h"
 
+#define USE_WIN32_COMPAT_IO 1
+
 extern void d_msg(const char *file, int line, int level, const char *fmt,...);
 extern DWORD   g_platform_id;
 
+// from MicroSoft SDK (KES) is the diff between Jan 1 1601 and Jan 1 1970
+#ifdef HAVE_MINGW
+#define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000UL //Not sure it works
+#else
+#define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000I64
+#endif
+
+#define WIN32_FILETIME_SCALE  10000000             // 100ns/second
 
 extern "C" void
 cygwin_conv_to_win32_path(const char *name, char *win32_name)
@@ -61,73 +71,29 @@ cygwin_conv_to_win32_path(const char *name, char *win32_name)
 }
 
 
-int
-open(const char *file, int flags, int mode)
+void
+wchar_win32_path(const char *name, WCHAR *win32_name)
 {
-    DWORD access = 0;
-    DWORD shareMode = 0;
-    DWORD create = 0;
-    DWORD msflags = 0;
-    HANDLE foo;
-    const char *remap = file;
-
-    if (flags & O_WRONLY) access = GENERIC_WRITE;
-    else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
-    else access = GENERIC_READ;
-    
-    if (flags & O_CREAT) create = CREATE_NEW;
-    else create = OPEN_EXISTING;
-    
-    if (flags & O_TRUNC) create = TRUNCATE_EXISTING;
-    
-    if (!(flags & O_EXCL))
-        shareMode = FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE;
-    
-    if (flags & O_APPEND)
-    {
-        printf("open...APPEND not implemented yet.");
-        exit(-1);
+    const char *fname = name;
+    while (*name) {
+        /* Check for Unix separator and convert to Win32 */
+        if (*name == '/') {
+            *win32_name++ = '\\';     /* convert char */
+        /* If Win32 separated that is "quoted", remove quote */
+        } else if (*name == '\\' && name[1] == '\\') {
+            *win32_name++ = '\\';
+            name++;                   /* skip first \ */
+        } else {
+            *win32_name++ = *name;    /* copy character */
+        }
+        name++;
+    }
+    /* Strip any trailing slash, if we stored something */
+    if (*fname != 0 && win32_name[-1] == '\\') {
+        win32_name[-1] = 0;
+    } else {
+        *win32_name = 0;
     }
-    
-    foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
-    if (INVALID_HANDLE_VALUE == foo)
-        return(int) -1;
-
-    return (int)foo;
-
-}
-
-
-int
-close(int fd)
-{
-    if (!CloseHandle((HANDLE)fd))
-        return -1;
-
-    return 0;
-}
-
-int
-write(int fd, const void *data, int32_t len)
-{
-    BOOL status;
-    DWORD bwrite;
-    status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
-    if (status) return bwrite;
-    return -1;
-}
-
-
-int
-read(int fd, void *data, int32_t len)
-{
-    BOOL status;
-    DWORD bread;
-
-    status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
-    if (status) return bread;
-
-    return -1;
 }
 
 int
@@ -154,11 +120,6 @@ lchown(const char *k, uid_t, gid_t)
     return 0;
 }
 
-int
-utime(const char *, struct utimbuf *)
-{
-    return -1;
-}
 
 
 long int
@@ -175,16 +136,30 @@ srandom(unsigned int seed)
 // /////////////////////////////////////////////////////////////////
 // convert from Windows concept of time to Unix concept of time
 // /////////////////////////////////////////////////////////////////
+void
+cvt_utime_to_ftime(const time_t  &time, FILETIME &wintime)
+{
+    uint64_t mstime = time;
+    mstime *= WIN32_FILETIME_SCALE;
+    mstime += WIN32_FILETIME_ADJUST;
+
+    #ifdef HAVE_MINGW
+    wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffUL);
+    #else
+    wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffI64);
+    #endif
+    wintime.dwHighDateTime = (DWORD) ((mstime>>32)& 0xffffffffUL);
+}
+
 time_t
-cvt(const FILETIME &time)
+cvt_ftime_to_utime(const FILETIME &time)
 {
     uint64_t mstime = time.dwHighDateTime;
     mstime <<= 32;
     mstime |= time.dwLowDateTime;
 
-    mstime /= 10000000;         // convert to seconds.
-    mstime -= 3234336I64*3600I64; // difference between jan 1, 1601
-                                  // and jan, 1 1970
+    mstime -= WIN32_FILETIME_ADJUST;
+    mstime /= WIN32_FILETIME_SCALE; // convert to seconds.
 
     return (time_t) (mstime & 0xffffffff);
 }
@@ -207,15 +182,16 @@ errorString(void)
     return (const char *) lpMsgBuf;
 }
 
+#ifndef HAVE_MINGW
+
 static int
 statDir(const char *file, struct stat *sb)
 {
     WIN32_FIND_DATA info;       // window's file info
-    sb->st_mode |= S_IFDIR;
 
-    if (file[1] == ':' && file[2] == 0)
-    {
+    if (file[1] == ':' && file[2] == 0) {
         d_msg(__FILE__, __LINE__, 99, "faking ROOT attrs(%s).\n", file);
+        sb->st_mode = S_IFDIR;
         sb->st_mode |= S_IREAD|S_IEXEC|S_IWRITE;
         time(&sb->st_ctime);
         time(&sb->st_mtime);
@@ -232,22 +208,25 @@ statDir(const char *file, struct stat *sb)
         return -1;
     }
 
-    sb->st_mode |= (S_IREAD | S_IEXEC);
-    if (!(info.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
-        sb->st_mode |= S_IWRITE;
-    
+    sb->st_mode = 0777;               /* start with everything */
+    if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
+        sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
     if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
-        sb->st_mode |= S_IRGRP;
+        sb->st_mode &= ~S_IRWXO; /* remove everything for other */
     if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
-        sb->st_mode |= S_IROTH;
+        sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
+    sb->st_mode |= S_IFDIR;
+
     sb->st_size = info.nFileSizeHigh;
     sb->st_size <<= 32;
     sb->st_size |= info.nFileSizeLow;
     sb->st_blksize = 4096;
     sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
-    sb->st_atime = cvt(info.ftLastAccessTime);
-    sb->st_mtime = cvt(info.ftLastWriteTime);
-    sb->st_ctime = cvt(info.ftCreationTime);
+
+    sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
+    sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
+    sb->st_ctime = cvt_ftime_to_utime(info.ftLastWriteTime);
+    FindClose(h);
 
     return 0;
 }
@@ -271,12 +250,10 @@ stat2(const char *file, struct stat *sb)
         errno = GetLastError();
         return -1;
     }
-    
-    if (attr & FILE_ATTRIBUTE_DIRECTORY) 
+
+    if (attr & FILE_ATTRIBUTE_DIRECTORY)
         return statDir(tmpbuf, sb);
 
-    sb->st_mode |= S_IFREG;
-    
     h = CreateFile(tmpbuf, GENERIC_READ,
                    FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
 
@@ -289,7 +266,7 @@ stat2(const char *file, struct stat *sb)
         errno = GetLastError();
         goto error;
     }
-    
+
     if (!GetFileInformationByHandle(h, &info)) {
         const char *err = errorString();
         d_msg(__FILE__, __LINE__, 99,
@@ -299,28 +276,30 @@ stat2(const char *file, struct stat *sb)
         errno = GetLastError();
         goto error;
     }
-    
+
     sb->st_dev = info.dwVolumeSerialNumber;
     sb->st_ino = info.nFileIndexHigh;
     sb->st_ino <<= 32;
     sb->st_ino |= info.nFileIndexLow;
     sb->st_nlink = (short)info.nNumberOfLinks;
-    sb->st_mode |= (S_IREAD | S_IEXEC);
-    if (!(info.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
-        sb->st_mode |= S_IWRITE;
 
+    sb->st_mode = 0777;               /* start with everything */
+    if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
+        sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
     if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
-        sb->st_mode |= S_IRGRP;
+        sb->st_mode &= ~S_IRWXO; /* remove everything for other */
     if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
-        sb->st_mode |= S_IROTH;
+        sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
+    sb->st_mode |= S_IFREG;
+
     sb->st_size = info.nFileSizeHigh;
     sb->st_size <<= 32;
     sb->st_size |= info.nFileSizeLow;
     sb->st_blksize = 4096;
     sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
-    sb->st_atime = cvt(info.ftLastAccessTime);
-    sb->st_mtime = cvt(info.ftLastWriteTime);
-    sb->st_ctime = cvt(info.ftCreationTime);
+    sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
+    sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
+    sb->st_ctime = cvt_ftime_to_utime(info.ftLastWriteTime);
 
 error:
     CloseHandle(h);
@@ -333,13 +312,36 @@ stat(const char *file, struct stat *sb)
     WIN32_FILE_ATTRIBUTE_DATA data;
     errno = 0;
 
+
     memset(sb, 0, sizeof(*sb));
 
     if (g_platform_id == VER_PLATFORM_WIN32_WINDOWS)
         return stat2(file, sb);
 
+    // otherwise we're on NT
+#if 0
+    WCHAR buf[32767];
+    buf[0] = '\\';
+    buf[1] = '\\';
+    buf[2] = '?';
+    buf[3] = '\\';
+
+    wchar_win32_path(file, buf+4);
+
+    if (!GetFileAttributesExW((WCHAR *)buf, GetFileExInfoStandard, &data))
+        return stat2(file, sb);
+#else
     if (!GetFileAttributesEx(file, GetFileExInfoStandard, &data))
         return stat2(file, sb);
+#endif
+
+    sb->st_mode = 0777;               /* start with everything */
+    if (data.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
+        sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
+    if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
+        sb->st_mode &= ~S_IRWXO; /* remove everything for other */
+    if (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
+        sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
 
     if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
         sb->st_mode |= S_IFDIR;
@@ -347,25 +349,19 @@ stat(const char *file, struct stat *sb)
         sb->st_mode |= S_IFREG;
 
     sb->st_nlink = 1;
-    sb->st_mode |= (S_IREAD | S_IEXEC);
-    if (!(data.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
-        sb->st_mode |= S_IWRITE;
-
-    if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
-        sb->st_mode |= S_IRGRP;
-    if (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
-        sb->st_mode |= S_IROTH;
     sb->st_size = data.nFileSizeHigh;
     sb->st_size <<= 32;
     sb->st_size |= data.nFileSizeLow;
     sb->st_blksize = 4096;
     sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
-    sb->st_atime = cvt(data.ftLastAccessTime);
-    sb->st_mtime = cvt(data.ftLastWriteTime);
-    sb->st_ctime = cvt(data.ftCreationTime);
+    sb->st_atime = cvt_ftime_to_utime(data.ftLastAccessTime);
+    sb->st_mtime = cvt_ftime_to_utime(data.ftLastWriteTime);
+    sb->st_ctime = cvt_ftime_to_utime(data.ftLastWriteTime);
     return 0;
 }
 
+#endif //HAVE_MINGW
+
 int
 lstat(const char *file, struct stat *sb)
 {
@@ -376,7 +372,7 @@ void
 sleep(int sec)
 {
     Sleep(sec * 1000);
-}    
+}
 
 int
 geteuid(void)
@@ -389,11 +385,6 @@ execvp(const char *, char *[]) {
     return -1;
 }
 
-int
-dup2(int, int)
-{
-    return -1;
-}
 
 int
 fork(void)
@@ -419,32 +410,13 @@ readlink(const char *, char *, int)
     return -1;
 }
 
-int
-lseek(int fd, int offset, int whence)
-{
-    DWORD method = 0;
-    switch (whence) {
-    case SEEK_SET :
-        method = FILE_BEGIN;
-        break;
-    case SEEK_CUR:
-        method = FILE_CURRENT;
-        break;
-    case SEEK_END:
-        method = FILE_END;
-        break;
-    default:
-        return -1;
-    }
-    
-    return SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method);
-}
 
+#ifndef HAVE_MINGW
 int
 strcasecmp(const char *s1, const char *s2)
 {
     register int ch1, ch2;
-    
+
     if (s1==s2)
         return 0;       /* strings are equal if same object. */
     else if (!s1)
@@ -458,29 +430,31 @@ strcasecmp(const char *s1, const char *s2)
         s1++;
         s2++;
     } while (ch1 != 0 && tolower(ch1) == tolower(ch2));
-    
+
   return(ch1 - ch2);
 }
+#endif //HAVE_MINGW
 
 int
 strncasecmp(const char *s1, const char *s2, int len)
 {
     register int ch1, ch2;
-    
+
     if (s1==s2)
         return 0;       /* strings are equal if same object. */
     else if (!s1)
         return -1;
     else if (!s2)
         return 1;
-    do
+    while (len--)
     {
         ch1 = *s1;
         ch2 = *s2;
         s1++;
         s2++;
-    } while (len-- && ch1 != 0 && tolower(ch1) == tolower(ch2));
-    
+        if (ch1 == 0 || tolower(ch1) != tolower(ch2)) break;
+    } 
+
     return(ch1 - ch2);
 }
 
@@ -497,16 +471,20 @@ gettimeofday(struct timeval *tv, struct timezone *)
     int64_t _100nsec = tmp.dwHighDateTime;
     _100nsec <<= 32;
     _100nsec |= tmp.dwLowDateTime;
-    _100nsec -= (3234336I64*3600I64 * 10000000I64);
+    _100nsec -= WIN32_FILETIME_ADJUST;
+
     tv->tv_sec =(long) (_100nsec / 10000000);
     tv->tv_usec = (long) ((_100nsec % 10000000)/10);
     return 0;
-    
+
 }
 
 int
-syslog(int, const char *, const char *)
+syslog(int type, const char *fmt, const char *msg)
 {
+/*#ifndef HAVE_CONSOLE
+    MessageBox(NULL, msg, "Bacula", MB_OK);
+#endif*/
     return 0;
 }
 
@@ -522,7 +500,6 @@ getgrgid(uid_t)
     return NULL;
 }
 
-
 // implement opendir/readdir/closedir on top of window's API
 typedef struct _dir
 {
@@ -539,12 +516,12 @@ opendir(const char *path)
     int max_len = strlen(path) + 16;
     _dir *rval = NULL;
     if (path == NULL) return NULL;
-    
+
     rval = (_dir *)malloc(sizeof(_dir));
     if (rval == NULL) return NULL;
     char *tspec = (char *)malloc(max_len);
     if (tspec == NULL) goto err1;
-    
+
     if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS) {
         // allow path to be 32767 bytes
         tspec[0] = '\\';
@@ -552,10 +529,11 @@ opendir(const char *path)
         tspec[2] = '?';
         tspec[3] = '\\';
         tspec[4] = 0;
-        cygwin_conv_to_win32_path(path, tspec+4); 
+        cygwin_conv_to_win32_path(path, tspec+4);
     } else {
         cygwin_conv_to_win32_path(path, tspec);
     }
+
     strncat(tspec, "\\*", max_len);
     rval->spec = tspec;
 
@@ -577,7 +555,7 @@ err1:
     free(rval);
     return NULL;
 }
-    
+
 int
 closedir(DIR *dirp)
 {
@@ -616,6 +594,7 @@ copyin(struct dirent &dp, const char *fname)
         *cp = 0;
     return dp.d_reclen;
 }
+
 int
 readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
 {
@@ -636,7 +615,6 @@ readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
     return 0;
 }
 
-
 int
 inet_aton(const char *a, struct in_addr *inp)
 {
@@ -702,10 +680,10 @@ WSA_Init(void)
 {
     WORD wVersionRequested = MAKEWORD( 1, 1);
     WSADATA wsaData;
-    
+
     int err = WSAStartup(wVersionRequested, &wsaData);
-    
-    
+
+
     if (err != 0)
     {
         printf("Can not start Windows Sockets\n");
@@ -735,7 +713,7 @@ win32_getcwd(char *buf, int maxlen)
        buf[n] = '\\';
        buf[n+1] = 0;
    }
-   
+
    return buf;
 }
 
@@ -783,6 +761,10 @@ winver::winver(void)
     snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %d.%d.%d",
              platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
 
+#if 0
+    HANDLE h = CreateFile("G:\\foobar", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
+    CloseHandle(h);
+#endif
 #if 0
     BPIPE *b = open_bpipe("ls -l", 10, "r");
     char buf[1024];
@@ -792,26 +774,40 @@ winver::winver(void)
     close_bpipe(b);
 #endif
 }
-BOOL CreateChildProcess(VOID); 
-VOID WriteToPipe(VOID); 
-VOID ReadFromPipe(VOID); 
-VOID ErrorExit(LPTSTR); 
-VOID ErrMsg(LPTSTR, BOOL); 
 
+BOOL CreateChildProcess(VOID);
+VOID WriteToPipe(VOID);
+VOID ReadFromPipe(VOID);
+VOID ErrorExit(LPTSTR);
+VOID ErrMsg(LPTSTR, BOOL);
+
+/**
+ * Check for a quoted path,  if an absolute path name is given and it contains
+ * spaces it will need to be quoted.  i.e.  "c:/Program Files/foo/bar.exe"
+ * CreateProcess() says the best way to ensure proper results with executables
+ * with spaces in path or filename is to quote the string.
+ */
 const char *
 getArgv0(const char *cmdline)
 {
-    const char *cp = cmdline;
 
-    while (*cp && !isspace(*cp)) cp++;
+    int inquote = 0;
+    for (const char *cp = cmdline; *cp; cp++)
+    {
+        if (*cp == '"') {
+            inquote = !inquote;
+        }
+        if (!inquote && isspace(*cp))
+            break;
+    }
 
+        
     int len = cp - cmdline;
     char *rval = (char *)malloc(len+1);
 
     cp = cmdline;
     char *rp = rval;
+    
     while (len--)
         *rp++ = *cp++;
 
@@ -819,19 +815,26 @@ getArgv0(const char *cmdline)
     return rval;
 }
 
+
+/**
+ * OK, so it would seem CreateProcess only handles true executables:
+ *  .com or .exe files.
+ * So test to see whether we're getting a .bat file and if so grab
+ * $COMSPEC value and pass batch file to it.
+ */
 HANDLE
-CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err) 
-{ 
-    PROCESS_INFORMATION piProcInfo; 
+CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err)
+{
+    PROCESS_INFORMATION piProcInfo;
     STARTUPINFO siStartInfo;
-    BOOL bFuncRetn = FALSE; 
-    
-    // Set up members of the PROCESS_INFORMATION structure. 
-    
+    BOOL bFuncRetn = FALSE;
+
+    // Set up members of the PROCESS_INFORMATION structure.
+
     ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
-    
-    // Set up members of the STARTUPINFO structure. 
-    
+
+    // Set up members of the STARTUPINFO structure.
+
     ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
     siStartInfo.cb = sizeof(STARTUPINFO);
     // setup new process to use supplied handles for stdin,stdout,stderr
@@ -843,7 +846,7 @@ CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err)
         siStartInfo.hStdInput = in;
     else
         siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
-    
+
     if (out != INVALID_HANDLE_VALUE)
         siStartInfo.hStdOutput = out;
     else
@@ -852,69 +855,56 @@ CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err)
         siStartInfo.hStdError = err;
     else
         siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
-    // Create the child process. 
+    // Create the child process.
+
+    char exeFile[256];
+
+    const char *comspec = getenv("COMSPEC");
     
-    char cmdLine[1024];
-    char exeFile[1024];
-    // retrive the first compont of the command line which should be the
-    // executable 
-    const char *exeName = getArgv0(cmdline);
-    // check to see if absolute path was passed to us already?
-    if (exeName[1] != ':'
-        || (strchr(cmdline, '/') == NULL
-            && strchr(cmdline, '\\') == NULL))
-    {
-        // only command name so perform search of PATH to find 
-        char *file;
-        DWORD rval = SearchPath(NULL,
-                                exeName,
-                                ".exe",
-                                sizeof(exeFile),
-                                exeFile,
-                                &file);
-        if (rval == 0)
-            return INVALID_HANDLE_VALUE;
-        if (rval > sizeof(exeFile))
-            return INVALID_HANDLE_VALUE;
+    if (comspec == NULL) // should never happen
+        return INVALID_HANDLE_VALUE;
 
-    }
-    else 
-        strcpy(exeFile, exeName);
+    char *cmdLine = (char *)alloca(strlen(cmdline) + strlen(comspec) + 16);
+    
+    strcpy(exeFile, comspec);
+    strcpy(cmdLine, comspec);
+    strcat(cmdLine, " /c ");
+    strcat(cmdLine, cmdline);
 
-    // exeFile now has absolute path to program to execute.
-    free((void *)exeName);
-    // copy original command line to pass to create process
-    strcpy(cmdLine, cmdline);
     // try to execute program
-    bFuncRetn = CreateProcess(exeFile, 
-                              cmdLine, // command line 
-                              NULL, // process security attributes 
-                              NULL, // primary thread security attributes 
-                              TRUE, // handles are inherited 
-                              0, // creation flags 
-                              NULL, // use parent's environment 
-                              NULL, // use parent's current directory 
-                              &siStartInfo, // STARTUPINFO pointer 
+    bFuncRetn = CreateProcess(exeFile,
+                              cmdLine, // command line
+                              NULL, // process security attributes
+                              NULL, // primary thread security attributes
+                              TRUE, // handles are inherited
+                              0, // creation flags
+                              NULL, // use parent's environment
+                              NULL, // use parent's current directory
+                              &siStartInfo, // STARTUPINFO pointer
                               &piProcInfo); // receives PROCESS_INFORMATION
-    
+
     if (bFuncRetn == 0) {
         ErrorExit("CreateProcess failed\n");
+        const char *err = errorString();
+        d_msg(__FILE__, __LINE__, 99,
+              "CreateProcess(%s, %s, ...)=%s\n", exeFile, cmdLine, err);
+        LocalFree((void *)err);
         return INVALID_HANDLE_VALUE;
     }
     // we don't need a handle on the process primary thread so we close
     // this now.
     CloseHandle(piProcInfo.hThread);
-    
+
     return piProcInfo.hProcess;
 }
 
+
 void
-ErrorExit (LPTSTR lpszMessage) 
-{ 
+ErrorExit (LPTSTR lpszMessage)
+{
     d_msg(__FILE__, __LINE__, 0, "%s", lpszMessage);
-} 
+}
+
 
 /*
 typedef struct s_bpipe {
@@ -933,131 +923,135 @@ CloseIfValid(HANDLE handle)
     if (handle != INVALID_HANDLE_VALUE)
         CloseHandle(handle);
 }
-// include <io.h> causes to many conflicts with some of
-// the fuctions we define here.
-extern "C" {
-int __cdecl _open_osfhandle(long, int);
-}
 
+#ifndef HAVE_MINGW
 BPIPE *
 open_bpipe(char *prog, int wait, const char *mode)
 {
-    HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup, 
-        hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup, 
+    HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
+        hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup,
         hInputFile;
-    
-    SECURITY_ATTRIBUTES saAttr; 
 
-    BOOL fSuccess; 
+    SECURITY_ATTRIBUTES saAttr;
+
+    BOOL fSuccess;
 
-    hChildStdinRd = hChildStdinWr = hChildStdinWrDup = 
-        hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup = 
+    hChildStdinRd = hChildStdinWr = hChildStdinWrDup =
+        hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup =
         hInputFile = INVALID_HANDLE_VALUE;
-    
+
     BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
     memset((void *)bpipe, 0, sizeof(BPIPE));
 
     int mode_read = (mode[0] == 'r');
     int mode_write = (mode[0] == 'w' || mode[1] == 'w');
-    
-    
-    // Set the bInheritHandle flag so pipe handles are inherited. 
-    
-    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
-    saAttr.bInheritHandle = TRUE; 
-    saAttr.lpSecurityDescriptor = NULL; 
-    
+
+
+    // Set the bInheritHandle flag so pipe handles are inherited.
+
+    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
+    saAttr.bInheritHandle = TRUE;
+    saAttr.lpSecurityDescriptor = NULL;
+
     if (mode_read) {
-        
-        // Create a pipe for the child process's STDOUT. 
+
+        // Create a pipe for the child process's STDOUT.
         if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
             ErrorExit("Stdout pipe creation failed\n");
             goto cleanup;
         }
-        // Create noninheritable read handle and close the inheritable read 
-        // handle. 
-        
+        // Create noninheritable read handle and close the inheritable read
+        // handle.
+
         fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
                                    GetCurrentProcess(), &hChildStdoutRdDup , 0,
                                    FALSE,
                                    DUPLICATE_SAME_ACCESS);
-        if( !fSuccess ) {
+        if ( !fSuccess ) {
             ErrorExit("DuplicateHandle failed");
             goto cleanup;
         }
-        
+
         CloseHandle(hChildStdoutRd);
+        hChildStdoutRd = INVALID_HANDLE_VALUE;
     }
-    
+
     if (mode_write) {
-        
-        // Create a pipe for the child process's STDIN. 
-        
-        if (! CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
+
+        // Create a pipe for the child process's STDIN.
+
+        if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
             ErrorExit("Stdin pipe creation failed\n");
             goto cleanup;
         }
-        
-        // Duplicate the write handle to the pipe so it is not inherited. 
-        fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr, 
+
+        // Duplicate the write handle to the pipe so it is not inherited.
+        fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
                                    GetCurrentProcess(), &hChildStdinWrDup,
-                                   0, 
-                                   FALSE,                  // not inherited 
-                                   DUPLICATE_SAME_ACCESS); 
+                                   0,
+                                   FALSE,                  // not inherited
+                                   DUPLICATE_SAME_ACCESS);
         if (!fSuccess) {
             ErrorExit("DuplicateHandle failed");
             goto cleanup;
         }
-        
-        CloseHandle(hChildStdinWr); 
+
+        CloseHandle(hChildStdinWr);
+        hChildStdinWr = INVALID_HANDLE_VALUE;
     }
     // spawn program with redirected handles as appropriate
     bpipe->worker_pid = (pid_t)
-        CreateChildProcess(prog, // commandline
-                           hChildStdinRd, // stdin HANDLE
-                           hChildStdoutWr, // stdout HANDLE
-                           hChildStdoutWr);// stderr HANDLE
-    
+        CreateChildProcess(prog,             // commandline
+                           hChildStdinRd,    // stdin HANDLE
+                           hChildStdoutWr,   // stdout HANDLE
+                           hChildStdoutWr);  // stderr HANDLE
+
     if ((HANDLE) bpipe->worker_pid == INVALID_HANDLE_VALUE)
         goto cleanup;
-    
+
     bpipe->wait = wait;
     bpipe->worker_stime = time(NULL);
-    
+
     if (mode_read) {
         CloseHandle(hChildStdoutWr); // close our write side so when
                                      // process terminates we can
                                      // detect eof.
         // ugly but convert WIN32 HANDLE to FILE*
         int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
-        bpipe->rfd = _fdopen(rfd, "r");
+        if (rfd >= 0) {
+           bpipe->rfd = _fdopen(rfd, "r");
+        }
     }
     if (mode_write) {
         CloseHandle(hChildStdinRd); // close our read side so as not
                                     // to interfre with child's copy
         // ugly but convert WIN32 HANDLE to FILE*
         int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
-        bpipe->wfd = _fdopen(wfd, "w");
+        if (wfd >= 0) {
+           bpipe->wfd = _fdopen(wfd, "w");
+        }
     }
-    
+
     if (wait > 0) {
         bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
     }
-    
+
     return bpipe;
-    
+
 cleanup:
-    
+
     CloseIfValid(hChildStdoutRd);
     CloseIfValid(hChildStdoutRdDup);
     CloseIfValid(hChildStdinWr);
     CloseIfValid(hChildStdinWrDup);
-    
+
     free((void *) bpipe);
-    
+
     return NULL;
 }
 
+#endif //HAVE_MINGW
+
 int
 kill(int pid, int signal)
 {
@@ -1068,6 +1062,8 @@ kill(int pid, int signal)
     return rval;
 }
 
+#ifndef HAVE_MINGW
+
 int
 close_bpipe(BPIPE *bpipe)
 {
@@ -1077,19 +1073,17 @@ close_bpipe(BPIPE *bpipe)
 
     if (bpipe->wait) {
         int remaining_wait = bpipe->wait;
-        do 
-        {
+        do {
             DWORD exitCode;
-            if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode))
-            {
+            if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode)) {
                 const char *err = errorString();
                 rval = GetLastError();
-                d_msg(__FILE__, __LINE__, 0, 
+                d_msg(__FILE__, __LINE__, 0,
                       "GetExitCode error %s\n", err);
                 LocalFree((void *)err);
                 break;
             }
-            
+
             if (exitCode == STILL_ACTIVE) {
                 bmicrosleep(1, 0);             /* wait one second */
                 remaining_wait--;
@@ -1097,11 +1091,11 @@ close_bpipe(BPIPE *bpipe)
             else break;
         } while(remaining_wait);
     }
-    
+
     if (bpipe->timer_id) {
         stop_child_timer(bpipe->timer_id);
     }
-    free((void *)bpipe);    
+    free((void *)bpipe);
     return rval;
 }
 
@@ -1109,7 +1103,7 @@ int
 close_wpipe(BPIPE *bpipe)
 {
     int stat = 1;
-    
+
     if (bpipe->wfd) {
         fflush(bpipe->wfd);
         if (fclose(bpipe->wfd) != 0) {
@@ -1119,3 +1113,188 @@ close_wpipe(BPIPE *bpipe)
     }
     return stat;
 }
+
+#include "findlib/find.h"
+
+int
+utime(const char *fname, struct utimbuf *times)
+{
+    FILETIME acc, mod;
+    char tmpbuf[1024];
+
+    cygwin_conv_to_win32_path(fname, tmpbuf);
+
+    cvt_utime_to_ftime(times->actime, acc);
+    cvt_utime_to_ftime(times->modtime, mod);
+
+    HANDLE h = CreateFile(tmpbuf,
+                          FILE_WRITE_ATTRIBUTES,
+                          FILE_SHARE_WRITE,
+                          NULL,
+                          OPEN_EXISTING,
+                          0,
+                          NULL);
+
+    if (h == INVALID_HANDLE_VALUE) {
+        const char *err = errorString();
+        d_msg(__FILE__, __LINE__, 99,
+              "Cannot open file for utime(%s,...):%s\n", tmpbuf, err);
+        LocalFree((void *)err);
+        return -1;
+    }
+
+    int rval = SetFileTime(h, NULL, &acc, &mod) ? 0 : -1;
+
+    CloseHandle(h);
+
+    return rval;
+}
+
+#if USE_WIN32_COMPAT_IO
+
+int
+open(const char *file, int flags, int mode)
+{
+    return _open(file, flags|_O_BINARY, mode);
+
+}
+
+int
+close(int fd)
+{
+    int rval = _close(fd);
+    if (rval == -1)
+        rval = closesocket(fd);
+    return rval;
+}
+
+#ifndef HAVE_WXCONSOLE
+ssize_t
+read(int fd, void *buf, size_t len)
+{
+    return _read(fd, buf, len);
+}
+
+ssize_t
+write(int fd, const void *buf, size_t len)
+{
+    return _write(fd, buf, len);
+}
+#endif
+
+off_t
+lseek(int fd, off_t offset, int whence)
+{
+    return (off_t)_lseeki64(fd, offset, whence);
+}
+
+int
+dup2(int fd1, int fd2)
+{
+    return _dup2(fd1, fd2);
+}
+#else
+int
+open(const char *file, int flags, int mode)
+{
+    DWORD access = 0;
+    DWORD shareMode = 0;
+    DWORD create = 0;
+    DWORD msflags = 0;
+    HANDLE foo;
+    const char *remap = file;
+
+    if (flags & O_WRONLY) access = GENERIC_WRITE;
+    else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
+    else access = GENERIC_READ;
+
+    if (flags & O_CREAT) create = CREATE_NEW;
+    else create = OPEN_EXISTING;
+
+    if (flags & O_TRUNC) create = TRUNCATE_EXISTING;
+
+    if (!(flags & O_EXCL))
+        shareMode = FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE;
+
+    if (flags & O_APPEND)
+    {
+        printf("open...APPEND not implemented yet.");
+        exit(-1);
+    }
+
+    foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
+    if (INVALID_HANDLE_VALUE == foo)
+        return(int) -1;
+
+    return (int)foo;
+
+}
+
+
+int
+close(int fd)
+{
+    if (!CloseHandle((HANDLE)fd))
+        return -1;
+
+    return 0;
+}
+
+ssize_t
+write(int fd, const void *data, size_t len)
+{
+    BOOL status;
+    DWORD bwrite;
+    status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
+    if (status) return bwrite;
+    return -1;
+}
+
+
+ssize_t
+read(int fd, void *data, size_t len)
+{
+    BOOL status;
+    DWORD bread;
+
+    status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
+    if (status) return bread;
+    return -1;
+}
+
+off_t
+lseek(int fd, off_t offset, int whence)
+{
+    DWORD method = 0;
+    switch (whence) {
+    case SEEK_SET :
+        method = FILE_BEGIN;
+        break;
+    case SEEK_CUR:
+        method = FILE_CURRENT;
+        break;
+    case SEEK_END:
+        method = FILE_END;
+        break;
+    default:
+        return -1;
+    }
+
+    return SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method);
+}
+
+int
+dup2(int, int)
+{
+    return -1;
+}
+
+
+#endif
+
+#endif //HAVE_MINGW
+
+#ifdef HAVE_MINGW
+/* syslog function, added by Nicolas Boichat */
+void closelog() {}
+#endif //HAVE_MINGW