2 // compat.cpp -- compatibilty layer to make bacula-fd run
3 // natively under windows
5 // Copyright transferred from Raider Solutions, Inc to
6 // Kern Sibbald and John Walker by express permission.
8 // Copyright (C) 2004 Kern Sibbald and John Walker
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of
13 // the License, or (at your option) any later version.
15 // This program is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // General Public License for more details.
20 // You should have received a copy of the GNU General Public
21 // License along with this program; if not, write to the Free
22 // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
23 // MA 02111-1307, USA.
25 // Author : Christopher S. Hull
26 // Created On : Sat Jan 31 15:55:00 2004
34 #define USE_WIN32_COMPAT_IO 1
36 extern void d_msg(const char *file, int line, int level, const char *fmt,...);
37 extern DWORD g_platform_id;
39 // from CYGWIN (should be diff between Jan 1 1601 and Jan 1 1970
41 #define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000UL //Not sure it works
43 #define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000I64
46 #define WIN32_FILETIME_SCALE 10000000 // 100ns/second
49 cygwin_conv_to_win32_path(const char *name, char *win32_name)
51 const char *fname = name;
53 /* Check for Unix separator and convert to Win32 */
55 *win32_name++ = '\\'; /* convert char */
56 /* If Win32 separated that is "quoted", remove quote */
57 } else if (*name == '\\' && name[1] == '\\') {
59 name++; /* skip first \ */
61 *win32_name++ = *name; /* copy character */
65 /* Strip any trailing slash, if we stored something */
66 if (*fname != 0 && win32_name[-1] == '\\') {
75 wchar_win32_path(const char *name, WCHAR *win32_name)
77 const char *fname = name;
79 /* Check for Unix separator and convert to Win32 */
81 *win32_name++ = '\\'; /* convert char */
82 /* If Win32 separated that is "quoted", remove quote */
83 } else if (*name == '\\' && name[1] == '\\') {
85 name++; /* skip first \ */
87 *win32_name++ = *name; /* copy character */
91 /* Strip any trailing slash, if we stored something */
92 if (*fname != 0 && win32_name[-1] == '\\') {
106 chmod(const char *, mode_t)
112 chown(const char *k, uid_t, gid_t)
118 lchown(const char *k, uid_t, gid_t)
132 srandom(unsigned int seed)
136 // /////////////////////////////////////////////////////////////////
137 // convert from Windows concept of time to Unix concept of time
138 // /////////////////////////////////////////////////////////////////
140 cvt_utime_to_ftime(const time_t &time, FILETIME &wintime)
142 uint64_t mstime = time;
143 mstime *= WIN32_FILETIME_SCALE;
144 mstime += WIN32_FILETIME_ADJUST;
147 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffUL);
149 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffI64);
151 wintime.dwHighDateTime = (DWORD) ((mstime>>32)& 0xffffffffUL);
155 cvt_ftime_to_utime(const FILETIME &time)
157 uint64_t mstime = time.dwHighDateTime;
159 mstime |= time.dwLowDateTime;
161 mstime -= WIN32_FILETIME_ADJUST;
162 mstime /= WIN32_FILETIME_SCALE; // convert to seconds.
164 return (time_t) (mstime & 0xffffffff);
172 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
173 FORMAT_MESSAGE_FROM_SYSTEM |
174 FORMAT_MESSAGE_IGNORE_INSERTS,
177 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default lang
182 return (const char *) lpMsgBuf;
188 statDir(const char *file, struct stat *sb)
190 WIN32_FIND_DATA info; // window's file info
192 if (file[1] == ':' && file[2] == 0) {
193 d_msg(__FILE__, __LINE__, 99, "faking ROOT attrs(%s).\n", file);
194 sb->st_mode = S_IFDIR;
195 sb->st_mode |= S_IREAD|S_IEXEC|S_IWRITE;
201 HANDLE h = FindFirstFile(file, &info);
203 if (h == INVALID_HANDLE_VALUE) {
204 const char *err = errorString();
205 d_msg(__FILE__, __LINE__, 99, "FindFirstFile(%s):%s\n", file, err);
206 LocalFree((void *)err);
207 errno = GetLastError();
211 sb->st_mode = 0777; /* start with everything */
212 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
213 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
214 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
215 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
216 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
217 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
218 sb->st_mode |= S_IFDIR;
220 sb->st_size = info.nFileSizeHigh;
222 sb->st_size |= info.nFileSizeLow;
223 sb->st_blksize = 4096;
224 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
226 sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
227 sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
228 sb->st_ctime = cvt_ftime_to_utime(info.ftLastWriteTime);
235 stat2(const char *file, struct stat *sb)
237 BY_HANDLE_FILE_INFORMATION info;
241 cygwin_conv_to_win32_path(file, tmpbuf);
243 DWORD attr = GetFileAttributes(tmpbuf);
246 const char *err = errorString();
247 d_msg(__FILE__, __LINE__, 99,
248 "GetFileAttrubtes(%s): %s\n", tmpbuf, err);
249 LocalFree((void *)err);
250 errno = GetLastError();
254 if (attr & FILE_ATTRIBUTE_DIRECTORY)
255 return statDir(tmpbuf, sb);
257 h = CreateFile(tmpbuf, GENERIC_READ,
258 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
260 if (h == INVALID_HANDLE_VALUE) {
261 const char *err = errorString();
262 d_msg(__FILE__, __LINE__, 99,
263 "Cannot open file for stat (%s):%s\n", tmpbuf, err);
264 LocalFree((void *)err);
266 errno = GetLastError();
270 if (!GetFileInformationByHandle(h, &info)) {
271 const char *err = errorString();
272 d_msg(__FILE__, __LINE__, 99,
273 "GetfileInformationByHandle(%s): %s\n", tmpbuf, err);
274 LocalFree((void *)err);
276 errno = GetLastError();
280 sb->st_dev = info.dwVolumeSerialNumber;
281 sb->st_ino = info.nFileIndexHigh;
283 sb->st_ino |= info.nFileIndexLow;
284 sb->st_nlink = (short)info.nNumberOfLinks;
286 sb->st_mode = 0777; /* start with everything */
287 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
288 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
289 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
290 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
291 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
292 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
293 sb->st_mode |= S_IFREG;
295 sb->st_size = info.nFileSizeHigh;
297 sb->st_size |= info.nFileSizeLow;
298 sb->st_blksize = 4096;
299 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
300 sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
301 sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
302 sb->st_ctime = cvt_ftime_to_utime(info.ftLastWriteTime);
310 stat(const char *file, struct stat *sb)
312 WIN32_FILE_ATTRIBUTE_DATA data;
316 memset(sb, 0, sizeof(*sb));
318 if (g_platform_id == VER_PLATFORM_WIN32_WINDOWS)
319 return stat2(file, sb);
321 // otherwise we're on NT
329 wchar_win32_path(file, buf+4);
331 if (!GetFileAttributesExW((WCHAR *)buf, GetFileExInfoStandard, &data))
332 return stat2(file, sb);
334 if (!GetFileAttributesEx(file, GetFileExInfoStandard, &data))
335 return stat2(file, sb);
338 sb->st_mode = 0777; /* start with everything */
339 if (data.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
340 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
341 if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
342 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
343 if (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
344 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
346 if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
347 sb->st_mode |= S_IFDIR;
349 sb->st_mode |= S_IFREG;
352 sb->st_size = data.nFileSizeHigh;
354 sb->st_size |= data.nFileSizeLow;
355 sb->st_blksize = 4096;
356 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
357 sb->st_atime = cvt_ftime_to_utime(data.ftLastAccessTime);
358 sb->st_mtime = cvt_ftime_to_utime(data.ftLastWriteTime);
359 sb->st_ctime = cvt_ftime_to_utime(data.ftLastWriteTime);
366 lstat(const char *file, struct stat *sb)
368 return stat(file, sb);
384 execvp(const char *, char *[]) {
402 waitpid(int, int*, int)
408 readlink(const char *, char *, int)
416 strcasecmp(const char *s1, const char *s2)
418 register int ch1, ch2;
421 return 0; /* strings are equal if same object. */
432 } while (ch1 != 0 && tolower(ch1) == tolower(ch2));
439 strncasecmp(const char *s1, const char *s2, int len)
441 register int ch1, ch2;
444 return 0; /* strings are equal if same object. */
455 if (ch1 == 0 || tolower(ch1) != tolower(ch2)) break;
462 gettimeofday(struct timeval *tv, struct timezone *)
468 if (tv == NULL) return -1;
469 if (!SystemTimeToFileTime(&now, &tmp)) return -1;
471 int64_t _100nsec = tmp.dwHighDateTime;
473 _100nsec |= tmp.dwLowDateTime;
474 _100nsec -= WIN32_FILETIME_ADJUST;
476 tv->tv_sec =(long) (_100nsec / 10000000);
477 tv->tv_usec = (long) ((_100nsec % 10000000)/10);
483 syslog(int type, const char *fmt, const char *msg)
485 /*#ifndef HAVE_CONSOLE
486 MessageBox(NULL, msg, "Bacula", MB_OK);
503 // implement opendir/readdir/closedir on top of window's API
506 WIN32_FIND_DATA data; // window's file info
507 const char *spec; // the directory we're traversing
508 HANDLE dirh; // the search handle
509 BOOL valid; // the info in data field is valid
510 UINT32 offset; // pseudo offset for d_off
514 opendir(const char *path)
516 int max_len = strlen(path) + 16;
518 if (path == NULL) return NULL;
520 rval = (_dir *)malloc(sizeof(_dir));
521 if (rval == NULL) return NULL;
522 char *tspec = (char *)malloc(max_len);
523 if (tspec == NULL) goto err1;
525 if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS) {
526 // allow path to be 32767 bytes
532 cygwin_conv_to_win32_path(path, tspec+4);
534 cygwin_conv_to_win32_path(path, tspec);
537 strncat(tspec, "\\*", max_len);
540 rval->dirh = FindFirstFile(rval->spec, &rval->data);
541 d_msg(__FILE__, __LINE__,
542 99, "opendir(%s)\n\tspec=%s,\n\tFindFirstFile returns %d\n",
543 path, rval->spec, rval->dirh);
546 if (rval->dirh == INVALID_HANDLE_VALUE)
549 d_msg(__FILE__, __LINE__,
550 99, "\tFirstFile=%s\n", rval->data.cFileName);
553 free((void *)rval->spec);
562 _dir *dp = (_dir *)dirp;
564 free((void *)dp->spec);
570 typedef struct _WIN32_FIND_DATA {
571 DWORD dwFileAttributes;
572 FILETIME ftCreationTime;
573 FILETIME ftLastAccessTime;
574 FILETIME ftLastWriteTime;
579 TCHAR cFileName[MAX_PATH];
580 TCHAR cAlternateFileName[14];
581 } WIN32_FIND_DATA, *PWIN32_FIND_DATA;
585 copyin(struct dirent &dp, const char *fname)
589 char *cp = dp.d_name;
599 readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
602 _dir *dp = (_dir *)dirp;
604 entry->d_off = dp->offset;
605 dp->offset += copyin(*entry, dp->data.cFileName);
606 *result = entry; /* return entry address */
607 d_msg(__FILE__, __LINE__,
608 99, "readdir_r(%p, { d_name=\"%s\", d_reclen=%d, d_off=%d\n",
609 dirp, entry->d_name, entry->d_reclen, entry->d_off);
611 // d_msg(__FILE__, __LINE__, 99, "readdir_r !valid\n");
614 dp->valid = FindNextFile(dp->dirh, &dp->data);
619 inet_aton(const char *a, struct in_addr *inp)
623 uint32_t acc = 0, tmp = 0;
625 if (!isdigit(*a)) return 0;
628 tmp = (tmp * 10) + (*cp -'0');
629 else if (*cp == '.') {
630 if (tmp > 255) return 0;
631 acc = (acc << 8) + tmp;
637 if (dotc != 3) return 0;
643 nanosleep(const struct timespec *req, struct timespec *rem)
646 rem->tv_sec = rem->tv_nsec = 0;
647 Sleep((req->tv_sec * 1000) + (req->tv_nsec/100000));
652 init_signals(void terminate(int sig))
658 init_stack_dump(void)
665 pathconf(const char *path, int name)
669 if (strncmp(path, "\\\\?\\", 4) == 0)
681 WORD wVersionRequested = MAKEWORD( 1, 1);
684 int err = WSAStartup(wVersionRequested, &wsaData);
689 printf("Can not start Windows Sockets\n");
698 win32_chdir(const char *dir)
700 if (0 == SetCurrentDirectory(dir)) return -1;
705 win32_getcwd(char *buf, int maxlen)
707 int n = GetCurrentDirectory(maxlen, buf);
709 if (n == 0 || n > maxlen) return NULL;
711 if (n+1 > maxlen) return NULL;
720 #include "mswinver.h"
722 char WIN_VERSION_LONG[64];
723 char WIN_VERSION[32];
730 static winver INIT; // cause constructor to be called before main()
737 const char *version = "";
738 const char *platform = "";
739 OSVERSIONINFO osvinfo;
740 osvinfo.dwOSVersionInfoSize = sizeof(osvinfo);
742 // Get the current OS version
743 if (!GetVersionEx(&osvinfo)) {
745 platform = "Unknown";
748 switch (_mkversion(osvinfo.dwPlatformId, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion))
750 case MS_WINDOWS_95: (version = "Windows 95"); break;
751 case MS_WINDOWS_98: (version = "Windows 98"); break;
752 case MS_WINDOWS_ME: (version = "Windows ME"); break;
753 case MS_WINDOWS_NT4:(version = "Windows NT 4.0"); platform = "NT"; break;
754 case MS_WINDOWS_2K: (version = "Windows 2000");platform = "NT"; break;
755 case MS_WINDOWS_XP: (version = "Windows XP");platform = "NT"; break;
756 case MS_WINDOWS_S2003: (version = "Windows Server 2003");platform = "NT"; break;
757 default: version = "Windows ??"; break;
760 bstrncpy(WIN_VERSION_LONG, version, sizeof(WIN_VERSION_LONG));
761 snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %d.%d.%d",
762 platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
765 HANDLE h = CreateFile("G:\\foobar", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
769 BPIPE *b = open_bpipe("ls -l", 10, "r");
771 while (!feof(b->rfd)) {
772 fgets(buf, sizeof(buf), b->rfd);
778 BOOL CreateChildProcess(VOID);
779 VOID WriteToPipe(VOID);
780 VOID ReadFromPipe(VOID);
781 VOID ErrorExit(LPTSTR);
782 VOID ErrMsg(LPTSTR, BOOL);
785 * Check for a quoted path, if an absolute path name is given and it contains
786 * spaces it will need to be quoted. i.e. "c:/Program Files/foo/bar.exe"
787 * CreateProcess() says the best way to ensure proper results with executables
788 * with spaces in path or filename is to quote the string.
791 getArgv0(const char *cmdline)
795 for (const char *cp = cmdline; *cp; cp++)
800 if (!inquote && isspace(*cp))
805 int len = cp - cmdline;
806 char *rval = (char *)malloc(len+1);
819 * Check to see if filename has the batch file extention.
822 isBatchFile(const char *fname)
824 const char *ext = strrchr(fname, '.');
827 int rval = strncasecmp(ext, ".bat", 4);
834 * OK, so it would seem CreateProcess only handles true executables:
835 * .com or .exe files.
836 * So test to see whether we're getting a .bat file and if so grab
837 * $COMSPEC value and pass batch file to it.
840 CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err)
842 PROCESS_INFORMATION piProcInfo;
843 STARTUPINFO siStartInfo;
844 BOOL bFuncRetn = FALSE;
846 // Set up members of the PROCESS_INFORMATION structure.
848 ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
850 // Set up members of the STARTUPINFO structure.
852 ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
853 siStartInfo.cb = sizeof(STARTUPINFO);
854 // setup new process to use supplied handles for stdin,stdout,stderr
855 // if supplied handles are not used the send a copy of our STD_HANDLE
857 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
859 if (in != INVALID_HANDLE_VALUE)
860 siStartInfo.hStdInput = in;
862 siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
864 if (out != INVALID_HANDLE_VALUE)
865 siStartInfo.hStdOutput = out;
867 siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
868 if (err != INVALID_HANDLE_VALUE)
869 siStartInfo.hStdError = err;
871 siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
872 // Create the child process.
876 // retrive the first compont of the command line which should be the
878 const char *exeName = getArgv0(cmdline);
880 if (isBatchFile(exeName)) {
881 const char *comspec = getenv("COMSPEC");
882 if (comspec == NULL) // should never happen
883 return INVALID_HANDLE_VALUE;
885 free((void *)exeName);
886 strcpy(exeFile, comspec);
887 strcpy(cmdLine, comspec);
888 strcat(cmdLine, " /c ");
889 strcat(cmdLine, cmdline);
893 // check to see if absolute path was passed to us already?
894 // allow for case when absolute path is in quotes "C:/...."
895 int driveCheck = exeName[0] == '"' ? 2 : 1;
896 if (exeName[driveCheck] != ':'
897 || (strchr(cmdline, '/') == NULL
898 && strchr(cmdline, '\\') == NULL))
900 // only command name so perform search of PATH to find
902 DWORD rval = SearchPath(NULL,
909 return INVALID_HANDLE_VALUE;
910 if (rval > sizeof(exeFile))
911 return INVALID_HANDLE_VALUE;
915 cygwin_conv_to_win32_path(exeName, exeFile);
917 // exeFile now has absolute path to program to execute.
918 free((void *)exeName);
920 // copy original command line to pass to create process
921 strcpy(cmdLine, cmdline);
923 // try to execute program
924 bFuncRetn = CreateProcess(exeFile,
925 cmdLine, // command line
926 NULL, // process security attributes
927 NULL, // primary thread security attributes
928 TRUE, // handles are inherited
930 NULL, // use parent's environment
931 NULL, // use parent's current directory
932 &siStartInfo, // STARTUPINFO pointer
933 &piProcInfo); // receives PROCESS_INFORMATION
935 if (bFuncRetn == 0) {
936 ErrorExit("CreateProcess failed\n");
937 const char *err = errorString();
938 d_msg(__FILE__, __LINE__, 99,
939 "CreateProcess(%s, %s, ...)=%s\n", exeFile, cmdLine, err);
940 LocalFree((void *)err);
941 return INVALID_HANDLE_VALUE;
943 // we don't need a handle on the process primary thread so we close
945 CloseHandle(piProcInfo.hThread);
947 return piProcInfo.hProcess;
952 ErrorExit (LPTSTR lpszMessage)
954 d_msg(__FILE__, __LINE__, 0, "%s", lpszMessage);
959 typedef struct s_bpipe {
970 CloseIfValid(HANDLE handle)
972 if (handle != INVALID_HANDLE_VALUE)
978 open_bpipe(char *prog, int wait, const char *mode)
980 HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
981 hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup,
984 SECURITY_ATTRIBUTES saAttr;
988 hChildStdinRd = hChildStdinWr = hChildStdinWrDup =
989 hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup =
990 hInputFile = INVALID_HANDLE_VALUE;
992 BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
993 memset((void *)bpipe, 0, sizeof(BPIPE));
995 int mode_read = (mode[0] == 'r');
996 int mode_write = (mode[0] == 'w' || mode[1] == 'w');
999 // Set the bInheritHandle flag so pipe handles are inherited.
1001 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1002 saAttr.bInheritHandle = TRUE;
1003 saAttr.lpSecurityDescriptor = NULL;
1007 // Create a pipe for the child process's STDOUT.
1008 if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
1009 ErrorExit("Stdout pipe creation failed\n");
1012 // Create noninheritable read handle and close the inheritable read
1015 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
1016 GetCurrentProcess(), &hChildStdoutRdDup , 0,
1018 DUPLICATE_SAME_ACCESS);
1020 ErrorExit("DuplicateHandle failed");
1024 CloseHandle(hChildStdoutRd);
1025 hChildStdoutRd = INVALID_HANDLE_VALUE;
1030 // Create a pipe for the child process's STDIN.
1032 if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
1033 ErrorExit("Stdin pipe creation failed\n");
1037 // Duplicate the write handle to the pipe so it is not inherited.
1038 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
1039 GetCurrentProcess(), &hChildStdinWrDup,
1041 FALSE, // not inherited
1042 DUPLICATE_SAME_ACCESS);
1044 ErrorExit("DuplicateHandle failed");
1048 CloseHandle(hChildStdinWr);
1049 hChildStdinWr = INVALID_HANDLE_VALUE;
1051 // spawn program with redirected handles as appropriate
1052 bpipe->worker_pid = (pid_t)
1053 CreateChildProcess(prog, // commandline
1054 hChildStdinRd, // stdin HANDLE
1055 hChildStdoutWr, // stdout HANDLE
1056 hChildStdoutWr); // stderr HANDLE
1058 if ((HANDLE) bpipe->worker_pid == INVALID_HANDLE_VALUE)
1062 bpipe->worker_stime = time(NULL);
1065 CloseHandle(hChildStdoutWr); // close our write side so when
1066 // process terminates we can
1068 // ugly but convert WIN32 HANDLE to FILE*
1069 int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
1071 bpipe->rfd = _fdopen(rfd, "r");
1075 CloseHandle(hChildStdinRd); // close our read side so as not
1076 // to interfre with child's copy
1077 // ugly but convert WIN32 HANDLE to FILE*
1078 int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
1080 bpipe->wfd = _fdopen(wfd, "w");
1085 bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
1092 CloseIfValid(hChildStdoutRd);
1093 CloseIfValid(hChildStdoutRdDup);
1094 CloseIfValid(hChildStdinWr);
1095 CloseIfValid(hChildStdinWrDup);
1097 free((void *) bpipe);
1105 kill(int pid, int signal)
1108 if (!TerminateProcess((HANDLE)pid, (UINT) signal))
1110 CloseHandle((HANDLE)pid);
1117 close_bpipe(BPIPE *bpipe)
1120 if (bpipe->rfd) fclose(bpipe->rfd);
1121 if (bpipe->wfd) fclose(bpipe->wfd);
1124 int remaining_wait = bpipe->wait;
1127 if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode)) {
1128 const char *err = errorString();
1129 rval = GetLastError();
1130 d_msg(__FILE__, __LINE__, 0,
1131 "GetExitCode error %s\n", err);
1132 LocalFree((void *)err);
1136 if (exitCode == STILL_ACTIVE) {
1137 bmicrosleep(1, 0); /* wait one second */
1141 } while(remaining_wait);
1144 if (bpipe->timer_id) {
1145 stop_child_timer(bpipe->timer_id);
1147 free((void *)bpipe);
1152 close_wpipe(BPIPE *bpipe)
1158 if (fclose(bpipe->wfd) != 0) {
1166 #include "findlib/find.h"
1169 utime(const char *fname, struct utimbuf *times)
1174 cygwin_conv_to_win32_path(fname, tmpbuf);
1176 cvt_utime_to_ftime(times->actime, acc);
1177 cvt_utime_to_ftime(times->modtime, mod);
1179 HANDLE h = CreateFile(tmpbuf,
1180 FILE_WRITE_ATTRIBUTES,
1187 if (h == INVALID_HANDLE_VALUE) {
1188 const char *err = errorString();
1189 d_msg(__FILE__, __LINE__, 99,
1190 "Cannot open file for utime(%s,...):%s\n", tmpbuf, err);
1191 LocalFree((void *)err);
1195 int rval = SetFileTime(h, NULL, &acc, &mod) ? 0 : -1;
1202 #if USE_WIN32_COMPAT_IO
1205 open(const char *file, int flags, int mode)
1207 return _open(file, flags|_O_BINARY, mode);
1217 #ifndef HAVE_WXCONSOLE
1219 read(int fd, void *buf, size_t len)
1221 return _read(fd, buf, len);
1225 write(int fd, const void *buf, size_t len)
1227 return _write(fd, buf, len);
1232 lseek(int fd, off_t offset, int whence)
1234 return (off_t)_lseeki64(fd, offset, whence);
1238 dup2(int fd1, int fd2)
1240 return _dup2(fd1, fd2);
1244 open(const char *file, int flags, int mode)
1247 DWORD shareMode = 0;
1251 const char *remap = file;
1253 if (flags & O_WRONLY) access = GENERIC_WRITE;
1254 else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
1255 else access = GENERIC_READ;
1257 if (flags & O_CREAT) create = CREATE_NEW;
1258 else create = OPEN_EXISTING;
1260 if (flags & O_TRUNC) create = TRUNCATE_EXISTING;
1262 if (!(flags & O_EXCL))
1263 shareMode = FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE;
1265 if (flags & O_APPEND)
1267 printf("open...APPEND not implemented yet.");
1271 foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
1272 if (INVALID_HANDLE_VALUE == foo)
1283 if (!CloseHandle((HANDLE)fd))
1290 write(int fd, const void *data, size_t len)
1294 status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
1295 if (status) return bwrite;
1301 read(int fd, void *data, size_t len)
1306 status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
1307 if (status) return bread;
1312 lseek(int fd, off_t offset, int whence)
1317 method = FILE_BEGIN;
1320 method = FILE_CURRENT;
1329 return SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method);
1344 /* syslog function, added by Nicolas Boichat */