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 b_errno_win32 (1<<29)
36 #define USE_WIN32_COMPAT_IO 1
38 extern void d_msg(const char *file, int line, int level, const char *fmt,...);
39 extern DWORD g_platform_id;
41 // from MicroSoft SDK (KES) is the diff between Jan 1 1601 and Jan 1 1970
43 #define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000UL //Not sure it works
45 #define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000I64
48 #define WIN32_FILETIME_SCALE 10000000 // 100ns/second
51 cygwin_conv_to_win32_path(const char *name, char *win32_name)
53 const char *fname = name;
55 /* Check for Unix separator and convert to Win32 */
57 *win32_name++ = '\\'; /* convert char */
58 /* If Win32 separated that is "quoted", remove quote */
59 } else if (*name == '\\' && name[1] == '\\') {
61 name++; /* skip first \ */
63 *win32_name++ = *name; /* copy character */
67 /* Strip any trailing slash, if we stored something */
68 if (*fname != 0 && win32_name[-1] == '\\') {
77 wchar_win32_path(const char *name, WCHAR *win32_name)
79 const char *fname = name;
81 /* Check for Unix separator and convert to Win32 */
83 *win32_name++ = '\\'; /* convert char */
84 /* If Win32 separated that is "quoted", remove quote */
85 } else if (*name == '\\' && name[1] == '\\') {
87 name++; /* skip first \ */
89 *win32_name++ = *name; /* copy character */
93 /* Strip any trailing slash, if we stored something */
94 if (*fname != 0 && win32_name[-1] == '\\') {
106 int chmod(const char *, mode_t)
111 int chown(const char *k, uid_t, gid_t)
116 int lchown(const char *k, uid_t, gid_t)
122 bool fstype(const char *fname, char *fs, int fslen)
124 return true; /* accept anything */
136 srandom(unsigned int seed)
140 // /////////////////////////////////////////////////////////////////
141 // convert from Windows concept of time to Unix concept of time
142 // /////////////////////////////////////////////////////////////////
144 cvt_utime_to_ftime(const time_t &time, FILETIME &wintime)
146 uint64_t mstime = time;
147 mstime *= WIN32_FILETIME_SCALE;
148 mstime += WIN32_FILETIME_ADJUST;
151 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffUL);
153 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffI64);
155 wintime.dwHighDateTime = (DWORD) ((mstime>>32)& 0xffffffffUL);
159 cvt_ftime_to_utime(const FILETIME &time)
161 uint64_t mstime = time.dwHighDateTime;
163 mstime |= time.dwLowDateTime;
165 mstime -= WIN32_FILETIME_ADJUST;
166 mstime /= WIN32_FILETIME_SCALE; // convert to seconds.
168 return (time_t) (mstime & 0xffffffff);
176 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
177 FORMAT_MESSAGE_FROM_SYSTEM |
178 FORMAT_MESSAGE_IGNORE_INSERTS,
181 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default lang
186 return (const char *) lpMsgBuf;
192 statDir(const char *file, struct stat *sb)
194 WIN32_FIND_DATA info; // window's file info
196 if (file[1] == ':' && file[2] == 0) {
197 d_msg(__FILE__, __LINE__, 99, "faking ROOT attrs(%s).\n", file);
198 sb->st_mode = S_IFDIR;
199 sb->st_mode |= S_IREAD|S_IEXEC|S_IWRITE;
205 HANDLE h = FindFirstFile(file, &info);
207 if (h == INVALID_HANDLE_VALUE) {
208 const char *err = errorString();
209 d_msg(__FILE__, __LINE__, 99, "FindFirstFile(%s):%s\n", file, err);
210 LocalFree((void *)err);
211 errno = b_errno_win32;
215 sb->st_mode = 0777; /* start with everything */
216 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
217 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
218 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
219 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
220 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
221 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
222 sb->st_mode |= S_IFDIR;
224 sb->st_size = info.nFileSizeHigh;
226 sb->st_size |= info.nFileSizeLow;
227 sb->st_blksize = 4096;
228 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
230 sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
231 sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
232 sb->st_ctime = cvt_ftime_to_utime(info.ftCreationTime);
239 stat2(const char *file, struct stat *sb)
241 BY_HANDLE_FILE_INFORMATION info;
245 cygwin_conv_to_win32_path(file, tmpbuf);
247 DWORD attr = GetFileAttributes(tmpbuf);
250 const char *err = errorString();
251 d_msg(__FILE__, __LINE__, 99,
252 "GetFileAttrubtes(%s): %s\n", tmpbuf, err);
253 LocalFree((void *)err);
254 errno = b_errno_win32;
258 if (attr & FILE_ATTRIBUTE_DIRECTORY)
259 return statDir(tmpbuf, sb);
261 h = CreateFile(tmpbuf, GENERIC_READ,
262 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
264 if (h == INVALID_HANDLE_VALUE) {
265 const char *err = errorString();
266 d_msg(__FILE__, __LINE__, 99,
267 "Cannot open file for stat (%s):%s\n", tmpbuf, err);
268 LocalFree((void *)err);
270 errno = b_errno_win32;
274 if (!GetFileInformationByHandle(h, &info)) {
275 const char *err = errorString();
276 d_msg(__FILE__, __LINE__, 99,
277 "GetfileInformationByHandle(%s): %s\n", tmpbuf, err);
278 LocalFree((void *)err);
280 errno = b_errno_win32;
284 sb->st_dev = info.dwVolumeSerialNumber;
285 sb->st_ino = info.nFileIndexHigh;
287 sb->st_ino |= info.nFileIndexLow;
288 sb->st_nlink = (short)info.nNumberOfLinks;
289 if (sb->st_nlink > 1) {
290 d_msg(__FILE__, __LINE__, 99, "st_nlink=%d\n", sb->st_nlink);
293 sb->st_mode = 0777; /* start with everything */
294 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
295 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
296 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
297 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
298 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
299 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
300 sb->st_mode |= S_IFREG;
302 sb->st_size = info.nFileSizeHigh;
304 sb->st_size |= info.nFileSizeLow;
305 sb->st_blksize = 4096;
306 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
307 sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
308 sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
309 sb->st_ctime = cvt_ftime_to_utime(info.ftCreationTime);
317 stat(const char *file, struct stat *sb)
319 WIN32_FILE_ATTRIBUTE_DATA data;
323 memset(sb, 0, sizeof(*sb));
325 if (g_platform_id == VER_PLATFORM_WIN32_WINDOWS)
326 return stat2(file, sb);
328 // otherwise we're on NT
336 wchar_win32_path(file, buf+4);
338 if (!GetFileAttributesExW((WCHAR *)buf, GetFileExInfoStandard, &data))
339 return stat2(file, sb);
341 if (!GetFileAttributesEx(file, GetFileExInfoStandard, &data))
342 return stat2(file, sb);
345 sb->st_mode = 0777; /* start with everything */
346 if (data.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
347 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
348 if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
349 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
350 if (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
351 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
353 if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
354 sb->st_mode |= S_IFDIR;
356 sb->st_mode |= S_IFREG;
359 sb->st_size = data.nFileSizeHigh;
361 sb->st_size |= data.nFileSizeLow;
362 sb->st_blksize = 4096;
363 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
364 sb->st_atime = cvt_ftime_to_utime(data.ftLastAccessTime);
365 sb->st_mtime = cvt_ftime_to_utime(data.ftLastWriteTime);
366 sb->st_ctime = cvt_ftime_to_utime(data.ftCreationTime);
373 lstat(const char *file, struct stat *sb)
375 return stat(file, sb);
391 execvp(const char *, char *[]) {
412 waitpid(int, int*, int)
419 readlink(const char *, char *, int)
428 strcasecmp(const char *s1, const char *s2)
430 register int ch1, ch2;
433 return 0; /* strings are equal if same object. */
444 } while (ch1 != 0 && tolower(ch1) == tolower(ch2));
451 strncasecmp(const char *s1, const char *s2, int len)
453 register int ch1, ch2;
456 return 0; /* strings are equal if same object. */
467 if (ch1 == 0 || tolower(ch1) != tolower(ch2)) break;
474 gettimeofday(struct timeval *tv, struct timezone *)
484 if (!SystemTimeToFileTime(&now, &tmp)) {
485 errno = b_errno_win32;
489 int64_t _100nsec = tmp.dwHighDateTime;
491 _100nsec |= tmp.dwLowDateTime;
492 _100nsec -= WIN32_FILETIME_ADJUST;
494 tv->tv_sec =(long) (_100nsec / 10000000);
495 tv->tv_usec = (long) ((_100nsec % 10000000)/10);
501 syslog(int type, const char *fmt, const char *msg)
503 /*#ifndef HAVE_CONSOLE
504 MessageBox(NULL, msg, "Bacula", MB_OK);
521 // implement opendir/readdir/closedir on top of window's API
524 WIN32_FIND_DATA data; // window's file info
525 const char *spec; // the directory we're traversing
526 HANDLE dirh; // the search handle
527 BOOL valid; // the info in data field is valid
528 UINT32 offset; // pseudo offset for d_off
532 opendir(const char *path)
534 int max_len = strlen(path) + 16;
541 rval = (_dir *)malloc(sizeof(_dir));
542 if (rval == NULL) return NULL;
543 char *tspec = (char *)malloc(max_len);
544 if (tspec == NULL) return NULL;
546 if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS) {
547 // allow path to be 32767 bytes
553 cygwin_conv_to_win32_path(path, tspec+4);
555 cygwin_conv_to_win32_path(path, tspec);
558 strncat(tspec, "\\*", max_len);
561 rval->dirh = FindFirstFile(rval->spec, &rval->data);
562 d_msg(__FILE__, __LINE__,
563 99, "opendir(%s)\n\tspec=%s,\n\tFindFirstFile returns %d\n",
564 path, rval->spec, rval->dirh);
567 if (rval->dirh == INVALID_HANDLE_VALUE)
570 d_msg(__FILE__, __LINE__,
571 99, "\tFirstFile=%s\n", rval->data.cFileName);
575 free((void *)rval->spec);
577 errno = b_errno_win32;
584 _dir *dp = (_dir *)dirp;
586 free((void *)dp->spec);
592 typedef struct _WIN32_FIND_DATA {
593 DWORD dwFileAttributes;
594 FILETIME ftCreationTime;
595 FILETIME ftLastAccessTime;
596 FILETIME ftLastWriteTime;
601 TCHAR cFileName[MAX_PATH];
602 TCHAR cAlternateFileName[14];
603 } WIN32_FIND_DATA, *PWIN32_FIND_DATA;
607 copyin(struct dirent &dp, const char *fname)
611 char *cp = dp.d_name;
621 readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
623 _dir *dp = (_dir *)dirp;
625 entry->d_off = dp->offset;
626 dp->offset += copyin(*entry, dp->data.cFileName);
627 *result = entry; /* return entry address */
628 d_msg(__FILE__, __LINE__,
629 99, "readdir_r(%p, { d_name=\"%s\", d_reclen=%d, d_off=%d\n",
630 dirp, entry->d_name, entry->d_reclen, entry->d_off);
632 // d_msg(__FILE__, __LINE__, 99, "readdir_r !valid\n");
633 errno = b_errno_win32;
636 dp->valid = FindNextFile(dp->dirh, &dp->data);
641 * Dotted IP address to network address
647 inet_aton(const char *a, struct in_addr *inp)
650 uint32_t acc = 0, tmp = 0;
653 if (!isdigit(*cp)) { /* first char must be digit */
654 return 0; /* error */
658 tmp = (tmp * 10) + (*cp -'0');
659 } else if (*cp == '.' || *cp == 0) {
661 return 0; /* error */
663 acc = (acc << 8) + tmp;
667 return 0; /* error */
669 } while (*cp++ != 0);
670 if (dotc != 4) { /* want 3 .'s plus EOS */
671 return 0; /* error */
673 inp->s_addr = htonl(acc); /* store addr in network format */
678 nanosleep(const struct timespec *req, struct timespec *rem)
681 rem->tv_sec = rem->tv_nsec = 0;
682 Sleep((req->tv_sec * 1000) + (req->tv_nsec/100000));
687 init_signals(void terminate(int sig))
693 init_stack_dump(void)
700 pathconf(const char *path, int name)
704 if (strncmp(path, "\\\\?\\", 4) == 0)
716 WORD wVersionRequested = MAKEWORD( 1, 1);
719 int err = WSAStartup(wVersionRequested, &wsaData);
723 printf("Can not start Windows Sockets\n");
733 win32_chdir(const char *dir)
735 if (0 == SetCurrentDirectory(dir)) {
736 errno = b_errno_win32;
743 win32_getcwd(char *buf, int maxlen)
745 int n = GetCurrentDirectory(maxlen, buf);
747 if (n == 0 || n > maxlen) return NULL;
749 if (n+1 > maxlen) return NULL;
757 #include "mswinver.h"
759 char WIN_VERSION_LONG[64];
760 char WIN_VERSION[32];
767 static winver INIT; // cause constructor to be called before main()
774 const char *version = "";
775 const char *platform = "";
776 OSVERSIONINFO osvinfo;
777 osvinfo.dwOSVersionInfoSize = sizeof(osvinfo);
779 // Get the current OS version
780 if (!GetVersionEx(&osvinfo)) {
782 platform = "Unknown";
785 switch (_mkversion(osvinfo.dwPlatformId, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion))
787 case MS_WINDOWS_95: (version = "Windows 95"); break;
788 case MS_WINDOWS_98: (version = "Windows 98"); break;
789 case MS_WINDOWS_ME: (version = "Windows ME"); break;
790 case MS_WINDOWS_NT4:(version = "Windows NT 4.0"); platform = "NT"; break;
791 case MS_WINDOWS_2K: (version = "Windows 2000");platform = "NT"; break;
792 case MS_WINDOWS_XP: (version = "Windows XP");platform = "NT"; break;
793 case MS_WINDOWS_S2003: (version = "Windows Server 2003");platform = "NT"; break;
794 default: version = "Windows ??"; break;
797 bstrncpy(WIN_VERSION_LONG, version, sizeof(WIN_VERSION_LONG));
798 snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %d.%d.%d",
799 platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
802 HANDLE h = CreateFile("G:\\foobar", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
806 BPIPE *b = open_bpipe("ls -l", 10, "r");
808 while (!feof(b->rfd)) {
809 fgets(buf, sizeof(buf), b->rfd);
815 BOOL CreateChildProcess(VOID);
816 VOID WriteToPipe(VOID);
817 VOID ReadFromPipe(VOID);
818 VOID ErrorExit(LPTSTR);
819 VOID ErrMsg(LPTSTR, BOOL);
822 * Check for a quoted path, if an absolute path name is given and it contains
823 * spaces it will need to be quoted. i.e. "c:/Program Files/foo/bar.exe"
824 * CreateProcess() says the best way to ensure proper results with executables
825 * with spaces in path or filename is to quote the string.
828 getArgv0(const char *cmdline)
832 for (const char *cp = cmdline; *cp; cp++)
837 if (!inquote && isspace(*cp))
842 int len = cp - cmdline;
843 char *rval = (char *)malloc(len+1);
857 * OK, so it would seem CreateProcess only handles true executables:
858 * .com or .exe files.
859 * So test to see whether we're getting a .bat file and if so grab
860 * $COMSPEC value and pass batch file to it.
863 CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err)
865 PROCESS_INFORMATION piProcInfo;
866 STARTUPINFO siStartInfo;
867 BOOL bFuncRetn = FALSE;
869 // Set up members of the PROCESS_INFORMATION structure.
871 ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
873 // Set up members of the STARTUPINFO structure.
875 ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
876 siStartInfo.cb = sizeof(STARTUPINFO);
877 // setup new process to use supplied handles for stdin,stdout,stderr
878 // if supplied handles are not used the send a copy of our STD_HANDLE
880 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
882 if (in != INVALID_HANDLE_VALUE)
883 siStartInfo.hStdInput = in;
885 siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
887 if (out != INVALID_HANDLE_VALUE)
888 siStartInfo.hStdOutput = out;
890 siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
891 if (err != INVALID_HANDLE_VALUE)
892 siStartInfo.hStdError = err;
894 siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
895 // Create the child process.
899 const char *comspec = getenv("COMSPEC");
901 if (comspec == NULL) // should never happen
902 return INVALID_HANDLE_VALUE;
904 char *cmdLine = (char *)alloca(strlen(cmdline) + strlen(comspec) + 16);
906 strcpy(exeFile, comspec);
907 strcpy(cmdLine, comspec);
908 strcat(cmdLine, " /c ");
909 strcat(cmdLine, cmdline);
911 // try to execute program
912 bFuncRetn = CreateProcess(exeFile,
913 cmdLine, // command line
914 NULL, // process security attributes
915 NULL, // primary thread security attributes
916 TRUE, // handles are inherited
918 NULL, // use parent's environment
919 NULL, // use parent's current directory
920 &siStartInfo, // STARTUPINFO pointer
921 &piProcInfo); // receives PROCESS_INFORMATION
923 if (bFuncRetn == 0) {
924 ErrorExit("CreateProcess failed\n");
925 const char *err = errorString();
926 d_msg(__FILE__, __LINE__, 99,
927 "CreateProcess(%s, %s, ...)=%s\n", exeFile, cmdLine, err);
928 LocalFree((void *)err);
929 return INVALID_HANDLE_VALUE;
931 // we don't need a handle on the process primary thread so we close
933 CloseHandle(piProcInfo.hThread);
935 return piProcInfo.hProcess;
940 ErrorExit (LPTSTR lpszMessage)
942 d_msg(__FILE__, __LINE__, 0, "%s", lpszMessage);
947 typedef struct s_bpipe {
958 CloseIfValid(HANDLE handle)
960 if (handle != INVALID_HANDLE_VALUE)
966 open_bpipe(char *prog, int wait, const char *mode)
968 HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
969 hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup,
972 SECURITY_ATTRIBUTES saAttr;
976 hChildStdinRd = hChildStdinWr = hChildStdinWrDup =
977 hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup =
978 hInputFile = INVALID_HANDLE_VALUE;
980 BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
981 memset((void *)bpipe, 0, sizeof(BPIPE));
983 int mode_read = (mode[0] == 'r');
984 int mode_write = (mode[0] == 'w' || mode[1] == 'w');
987 // Set the bInheritHandle flag so pipe handles are inherited.
989 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
990 saAttr.bInheritHandle = TRUE;
991 saAttr.lpSecurityDescriptor = NULL;
995 // Create a pipe for the child process's STDOUT.
996 if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
997 ErrorExit("Stdout pipe creation failed\n");
1000 // Create noninheritable read handle and close the inheritable read
1003 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
1004 GetCurrentProcess(), &hChildStdoutRdDup , 0,
1006 DUPLICATE_SAME_ACCESS);
1008 ErrorExit("DuplicateHandle failed");
1012 CloseHandle(hChildStdoutRd);
1013 hChildStdoutRd = INVALID_HANDLE_VALUE;
1018 // Create a pipe for the child process's STDIN.
1020 if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
1021 ErrorExit("Stdin pipe creation failed\n");
1025 // Duplicate the write handle to the pipe so it is not inherited.
1026 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
1027 GetCurrentProcess(), &hChildStdinWrDup,
1029 FALSE, // not inherited
1030 DUPLICATE_SAME_ACCESS);
1032 ErrorExit("DuplicateHandle failed");
1036 CloseHandle(hChildStdinWr);
1037 hChildStdinWr = INVALID_HANDLE_VALUE;
1039 // spawn program with redirected handles as appropriate
1040 bpipe->worker_pid = (pid_t)
1041 CreateChildProcess(prog, // commandline
1042 hChildStdinRd, // stdin HANDLE
1043 hChildStdoutWr, // stdout HANDLE
1044 hChildStdoutWr); // stderr HANDLE
1046 if ((HANDLE) bpipe->worker_pid == INVALID_HANDLE_VALUE)
1050 bpipe->worker_stime = time(NULL);
1053 CloseHandle(hChildStdoutWr); // close our write side so when
1054 // process terminates we can
1056 // ugly but convert WIN32 HANDLE to FILE*
1057 int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
1059 bpipe->rfd = _fdopen(rfd, "r");
1063 CloseHandle(hChildStdinRd); // close our read side so as not
1064 // to interfre with child's copy
1065 // ugly but convert WIN32 HANDLE to FILE*
1066 int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
1068 bpipe->wfd = _fdopen(wfd, "w");
1073 bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
1080 CloseIfValid(hChildStdoutRd);
1081 CloseIfValid(hChildStdoutRdDup);
1082 CloseIfValid(hChildStdinWr);
1083 CloseIfValid(hChildStdinWrDup);
1085 free((void *) bpipe);
1086 errno = b_errno_win32; /* do GetLastError() for error code */
1093 kill(int pid, int signal)
1096 if (!TerminateProcess((HANDLE)pid, (UINT) signal)) {
1098 errno = b_errno_win32;
1100 CloseHandle((HANDLE)pid);
1107 close_bpipe(BPIPE *bpipe)
1110 int32_t remaining_wait = bpipe->wait;
1112 if (remaining_wait == 0) { /* wait indefinitely */
1113 remaining_wait = INT32_MAX;
1117 if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode)) {
1118 const char *err = errorString();
1119 rval = b_errno_win32;
1120 d_msg(__FILE__, __LINE__, 0,
1121 "GetExitCode error %s\n", err);
1122 LocalFree((void *)err);
1125 if (exitCode == STILL_ACTIVE) {
1126 if (remaining_wait <= 0) {
1127 rval = ETIME; /* timed out */
1130 bmicrosleep(1, 0); /* wait one second */
1132 } else if (exitCode != 0) {
1133 /* Truncate exit code as it doesn't seem to be correct */
1134 rval = (exitCode & 0xFF) | b_errno_exit;
1137 break; /* Shouldn't get here */
1141 if (bpipe->timer_id) {
1142 stop_child_timer(bpipe->timer_id);
1144 if (bpipe->rfd) fclose(bpipe->rfd);
1145 if (bpipe->wfd) fclose(bpipe->wfd);
1146 free((void *)bpipe);
1151 close_wpipe(BPIPE *bpipe)
1157 if (fclose(bpipe->wfd) != 0) {
1165 #include "findlib/find.h"
1168 utime(const char *fname, struct utimbuf *times)
1173 cygwin_conv_to_win32_path(fname, tmpbuf);
1175 cvt_utime_to_ftime(times->actime, acc);
1176 cvt_utime_to_ftime(times->modtime, mod);
1178 HANDLE h = CreateFile(tmpbuf,
1179 FILE_WRITE_ATTRIBUTES,
1186 if (h == INVALID_HANDLE_VALUE) {
1187 const char *err = errorString();
1188 d_msg(__FILE__, __LINE__, 99,
1189 "Cannot open file \"%s\" for utime(): ERR=%s", tmpbuf, err);
1190 LocalFree((void *)err);
1191 errno = b_errno_win32;
1195 int rval = SetFileTime(h, NULL, &acc, &mod) ? 0 : -1;
1198 errno = b_errno_win32;
1203 #if USE_WIN32_COMPAT_IO
1206 open(const char *file, int flags, int mode)
1208 return _open(file, flags|_O_BINARY, mode);
1213 * Note, this works only for a file. If you want
1214 * to close a socket, use closesocket().
1215 * Bacula has been modified in src/lib/bnet.c
1216 * to use closesocket().
1224 #ifndef HAVE_WXCONSOLE
1226 read(int fd, void *buf, ssize_t len)
1228 return _read(fd, buf, (size_t)len);
1232 write(int fd, const void *buf, ssize_t len)
1234 return _write(fd, buf, (size_t)len);
1239 lseek(int fd, off_t offset, int whence)
1241 return _lseeki64(fd, offset, whence);
1245 dup2(int fd1, int fd2)
1247 return _dup2(fd1, fd2);
1251 open(const char *file, int flags, int mode)
1254 DWORD shareMode = 0;
1258 const char *remap = file;
1260 if (flags & O_WRONLY) access = GENERIC_WRITE;
1261 else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
1262 else access = GENERIC_READ;
1264 if (flags & O_CREAT) create = CREATE_NEW;
1265 else create = OPEN_EXISTING;
1267 if (flags & O_TRUNC) create = TRUNCATE_EXISTING;
1269 if (!(flags & O_EXCL))
1270 shareMode = FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE;
1272 if (flags & O_APPEND) {
1273 printf("open...APPEND not implemented yet.");
1277 foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
1278 if (INVALID_HANDLE_VALUE == foo) {
1279 errno = b_errno_win32;
1290 if (!CloseHandle((HANDLE)fd)) {
1291 errno = b_errno_win32;
1299 write(int fd, const void *data, ssize_t len)
1303 status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
1304 if (status) return bwrite;
1305 errno = b_errno_win32;
1311 read(int fd, void *data, ssize_t len)
1316 status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
1317 if (status) return bread;
1318 errno = b_errno_win32;
1323 lseek(int fd, off_t offset, int whence)
1329 method = FILE_BEGIN;
1332 method = FILE_CURRENT;
1342 if ((val=SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method)) == INVALID_SET_FILE_POINTER) {
1343 errno = b_errno_win32;
1346 /* ***FIXME*** I doubt this works right */
1363 /* syslog function, added by Nicolas Boichat */