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] == '\\') {
78 wchar_2_UTF8(char *pszUTF, const WCHAR *pszUCS, int cchChar)
80 /* the return value is the number of bytes written to the buffer.
81 The number includes the byte for the null terminator. */
83 return WideCharToMultiByte (CP_UTF8,0,pszUCS,-1,pszUTF,cchChar,NULL,NULL);
87 UTF8_2_wchar(WCHAR *pszUCS, const char *pszUTF, int cchWideChar)
89 /* the return value is the number of wide characters written to the buffer. */
90 /* convert null terminated string from utf-8 to ucs2*/
91 return MultiByteToWideChar(CP_UTF8, 0, pszUTF, -1, pszUCS,cchWideChar);
98 wchar_win32_path(const char *name, WCHAR *win32_name)
100 const char *fname = name;
102 /* Check for Unix separator and convert to Win32 */
104 *win32_name++ = '\\'; /* convert char */
105 /* If Win32 separated that is "quoted", remove quote */
106 } else if (*name == '\\' && name[1] == '\\') {
107 *win32_name++ = '\\';
108 name++; /* skip first \ */
110 *win32_name++ = *name; /* copy character */
114 /* Strip any trailing slash, if we stored something */
115 if (*fname != 0 && win32_name[-1] == '\\') {
127 int chmod(const char *, mode_t)
132 int chown(const char *k, uid_t, gid_t)
137 int lchown(const char *k, uid_t, gid_t)
143 bool fstype(const char *fname, char *fs, int fslen)
145 return true; /* accept anything */
157 srandom(unsigned int seed)
161 // /////////////////////////////////////////////////////////////////
162 // convert from Windows concept of time to Unix concept of time
163 // /////////////////////////////////////////////////////////////////
165 cvt_utime_to_ftime(const time_t &time, FILETIME &wintime)
167 uint64_t mstime = time;
168 mstime *= WIN32_FILETIME_SCALE;
169 mstime += WIN32_FILETIME_ADJUST;
172 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffUL);
174 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffI64);
176 wintime.dwHighDateTime = (DWORD) ((mstime>>32)& 0xffffffffUL);
180 cvt_ftime_to_utime(const FILETIME &time)
182 uint64_t mstime = time.dwHighDateTime;
184 mstime |= time.dwLowDateTime;
186 mstime -= WIN32_FILETIME_ADJUST;
187 mstime /= WIN32_FILETIME_SCALE; // convert to seconds.
189 return (time_t) (mstime & 0xffffffff);
197 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
198 FORMAT_MESSAGE_FROM_SYSTEM |
199 FORMAT_MESSAGE_IGNORE_INSERTS,
202 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default lang
207 return (const char *) lpMsgBuf;
213 statDir(const char *file, struct stat *sb)
215 #if USE_WIN32_UNICODE
216 WIN32_FIND_DATAW info; // window's file info
218 WIN32_FIND_DATA info; // window's file info
221 if (file[1] == ':' && file[2] == 0) {
222 d_msg(__FILE__, __LINE__, 99, "faking ROOT attrs(%s).\n", file);
223 sb->st_mode = S_IFDIR;
224 sb->st_mode |= S_IREAD|S_IEXEC|S_IWRITE;
231 #if USE_WIN32_UNICODE
232 WCHAR szBuf[MAX_PATH_UNICODE];
233 UTF8_2_wchar(szBuf, file, MAX_PATH_UNICODE);
235 HANDLE h = FindFirstFileW(szBuf, &info);
237 HANDLE h = FindFirstFile(file, &info);
240 if (h == INVALID_HANDLE_VALUE) {
241 const char *err = errorString();
242 d_msg(__FILE__, __LINE__, 99, "FindFirstFile(%s):%s\n", file, err);
243 LocalFree((void *)err);
244 errno = b_errno_win32;
248 sb->st_mode = 0777; /* start with everything */
249 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
250 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
251 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
252 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
253 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
254 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
255 sb->st_mode |= S_IFDIR;
257 sb->st_size = info.nFileSizeHigh;
259 sb->st_size |= info.nFileSizeLow;
260 sb->st_blksize = 4096;
261 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
263 sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
264 sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
265 sb->st_ctime = cvt_ftime_to_utime(info.ftCreationTime);
272 stat2(const char *file, struct stat *sb)
274 BY_HANDLE_FILE_INFORMATION info;
278 cygwin_conv_to_win32_path(file, tmpbuf);
280 #if USE_WIN32_UNICODE
281 WCHAR szBuf[MAX_PATH_UNICODE];
282 UTF8_2_wchar(szBuf, tmpbuf, MAX_PATH_UNICODE);
284 DWORD attr = GetFileAttributesW(szBuf);
286 DWORD attr = GetFileAttributes(tmpbuf);
290 const char *err = errorString();
291 d_msg(__FILE__, __LINE__, 99,
292 "GetFileAttrubtes(%s): %s\n", tmpbuf, err);
293 LocalFree((void *)err);
294 errno = b_errno_win32;
298 if (attr & FILE_ATTRIBUTE_DIRECTORY)
299 return statDir(tmpbuf, sb);
301 h = CreateFile(tmpbuf, GENERIC_READ,
302 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
304 if (h == INVALID_HANDLE_VALUE) {
305 const char *err = errorString();
306 d_msg(__FILE__, __LINE__, 99,
307 "Cannot open file for stat (%s):%s\n", tmpbuf, err);
308 LocalFree((void *)err);
310 errno = b_errno_win32;
314 if (!GetFileInformationByHandle(h, &info)) {
315 const char *err = errorString();
316 d_msg(__FILE__, __LINE__, 99,
317 "GetfileInformationByHandle(%s): %s\n", tmpbuf, err);
318 LocalFree((void *)err);
320 errno = b_errno_win32;
324 sb->st_dev = info.dwVolumeSerialNumber;
325 sb->st_ino = info.nFileIndexHigh;
327 sb->st_ino |= info.nFileIndexLow;
328 sb->st_nlink = (short)info.nNumberOfLinks;
329 if (sb->st_nlink > 1) {
330 d_msg(__FILE__, __LINE__, 99, "st_nlink=%d\n", sb->st_nlink);
333 sb->st_mode = 0777; /* start with everything */
334 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
335 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
336 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
337 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
338 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
339 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
340 sb->st_mode |= S_IFREG;
342 sb->st_size = info.nFileSizeHigh;
344 sb->st_size |= info.nFileSizeLow;
345 sb->st_blksize = 4096;
346 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
347 sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
348 sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
349 sb->st_ctime = cvt_ftime_to_utime(info.ftCreationTime);
357 stat(const char *file, struct stat *sb)
359 WIN32_FILE_ATTRIBUTE_DATA data;
363 memset(sb, 0, sizeof(*sb));
365 if (g_platform_id == VER_PLATFORM_WIN32_WINDOWS)
366 return stat2(file, sb);
368 // otherwise we're on NT
376 wchar_win32_path(file, buf+4);
378 if (!GetFileAttributesExW((WCHAR *)buf, GetFileExInfoStandard, &data))
379 return stat2(file, sb);
381 #if USE_WIN32_UNICODE
382 WCHAR buf[MAX_PATH_UNICODE];
383 UTF8_2_wchar(buf, file, MAX_PATH_UNICODE);
384 if (!GetFileAttributesExW(buf, GetFileExInfoStandard, &data))
385 return stat2(file, sb);
387 if (!GetFileAttributesEx(file, GetFileExInfoStandard, &data))
388 return stat2(file, sb);
392 sb->st_mode = 0777; /* start with everything */
393 if (data.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
394 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
395 if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
396 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
397 if (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
398 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
400 if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
401 sb->st_mode |= S_IFDIR;
403 sb->st_mode |= S_IFREG;
406 sb->st_size = data.nFileSizeHigh;
408 sb->st_size |= data.nFileSizeLow;
409 sb->st_blksize = 4096;
410 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
411 sb->st_atime = cvt_ftime_to_utime(data.ftLastAccessTime);
412 sb->st_mtime = cvt_ftime_to_utime(data.ftLastWriteTime);
413 sb->st_ctime = cvt_ftime_to_utime(data.ftCreationTime);
420 lstat(const char *file, struct stat *sb)
422 return stat(file, sb);
438 execvp(const char *, char *[]) {
459 waitpid(int, int*, int)
466 readlink(const char *, char *, int)
475 strcasecmp(const char *s1, const char *s2)
477 register int ch1, ch2;
480 return 0; /* strings are equal if same object. */
491 } while (ch1 != 0 && tolower(ch1) == tolower(ch2));
498 strncasecmp(const char *s1, const char *s2, int len)
500 register int ch1, ch2;
503 return 0; /* strings are equal if same object. */
514 if (ch1 == 0 || tolower(ch1) != tolower(ch2)) break;
521 gettimeofday(struct timeval *tv, struct timezone *)
531 if (!SystemTimeToFileTime(&now, &tmp)) {
532 errno = b_errno_win32;
536 int64_t _100nsec = tmp.dwHighDateTime;
538 _100nsec |= tmp.dwLowDateTime;
539 _100nsec -= WIN32_FILETIME_ADJUST;
541 tv->tv_sec =(long) (_100nsec / 10000000);
542 tv->tv_usec = (long) ((_100nsec % 10000000)/10);
548 syslog(int type, const char *fmt, const char *msg)
550 /*#ifndef HAVE_CONSOLE
551 MessageBox(NULL, msg, "Bacula", MB_OK);
568 // implement opendir/readdir/closedir on top of window's API
571 #if USE_WIN32_UNICODE
572 WIN32_FIND_DATAW data; // window's file info
574 WIN32_FIND_DATA data; // window's file info
576 const char *spec; // the directory we're traversing
577 HANDLE dirh; // the search handle
578 BOOL valid; // the info in data field is valid
579 UINT32 offset; // pseudo offset for d_off
583 opendir(const char *path)
585 int max_len = strlen(path) + 16;
592 rval = (_dir *)malloc(sizeof(_dir));
593 if (rval == NULL) return NULL;
594 char *tspec = (char *)malloc(max_len);
595 if (tspec == NULL) return NULL;
597 if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS) {
598 // allow path to be 32767 bytes
604 cygwin_conv_to_win32_path(path, tspec+4);
606 cygwin_conv_to_win32_path(path, tspec);
609 strncat(tspec, "\\*", max_len);
613 #if USE_WIN32_UNICODE
614 WCHAR wcBuf[MAX_PATH_UNICODE];
615 UTF8_2_wchar(wcBuf,rval->spec, MAX_PATH_UNICODE);
616 rval->dirh = FindFirstFileW(wcBuf, &rval->data);
618 rval->dirh = FindFirstFile(rval->spec, &rval->data);
621 d_msg(__FILE__, __LINE__,
622 99, "opendir(%s)\n\tspec=%s,\n\tFindFirstFile returns %d\n",
623 path, rval->spec, rval->dirh);
626 if (rval->dirh == INVALID_HANDLE_VALUE)
629 d_msg(__FILE__, __LINE__,
630 99, "\tFirstFile=%s\n", rval->data.cFileName);
634 free((void *)rval->spec);
636 errno = b_errno_win32;
643 _dir *dp = (_dir *)dirp;
645 free((void *)dp->spec);
651 typedef struct _WIN32_FIND_DATA {
652 DWORD dwFileAttributes;
653 FILETIME ftCreationTime;
654 FILETIME ftLastAccessTime;
655 FILETIME ftLastWriteTime;
660 TCHAR cFileName[MAX_PATH];
661 TCHAR cAlternateFileName[14];
662 } WIN32_FIND_DATA, *PWIN32_FIND_DATA;
666 copyin(struct dirent &dp, const char *fname)
670 char *cp = dp.d_name;
680 readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
682 _dir *dp = (_dir *)dirp;
684 entry->d_off = dp->offset;
686 #if USE_WIN32_UNICODE
687 char szBuf[MAX_PATH_UTF8];
688 wchar_2_UTF8(szBuf,dp->data.cFileName);
689 dp->offset += copyin(*entry, szBuf);
691 dp->offset += copyin(*entry, dp->data.cFileName);
694 *result = entry; /* return entry address */
695 d_msg(__FILE__, __LINE__,
696 99, "readdir_r(%p, { d_name=\"%s\", d_reclen=%d, d_off=%d\n",
697 dirp, entry->d_name, entry->d_reclen, entry->d_off);
699 // d_msg(__FILE__, __LINE__, 99, "readdir_r !valid\n");
700 errno = b_errno_win32;
704 #if USE_WIN32_UNICODE
705 dp->valid = FindNextFileW(dp->dirh, &dp->data);
707 dp->valid = FindNextFileA(dp->dirh, &dp->data);
714 * Dotted IP address to network address
720 inet_aton(const char *a, struct in_addr *inp)
723 uint32_t acc = 0, tmp = 0;
726 if (!isdigit(*cp)) { /* first char must be digit */
727 return 0; /* error */
731 tmp = (tmp * 10) + (*cp -'0');
732 } else if (*cp == '.' || *cp == 0) {
734 return 0; /* error */
736 acc = (acc << 8) + tmp;
740 return 0; /* error */
742 } while (*cp++ != 0);
743 if (dotc != 4) { /* want 3 .'s plus EOS */
744 return 0; /* error */
746 inp->s_addr = htonl(acc); /* store addr in network format */
751 nanosleep(const struct timespec *req, struct timespec *rem)
754 rem->tv_sec = rem->tv_nsec = 0;
755 Sleep((req->tv_sec * 1000) + (req->tv_nsec/100000));
760 init_signals(void terminate(int sig))
766 init_stack_dump(void)
773 pathconf(const char *path, int name)
777 if (strncmp(path, "\\\\?\\", 4) == 0)
789 WORD wVersionRequested = MAKEWORD( 1, 1);
792 int err = WSAStartup(wVersionRequested, &wsaData);
796 printf("Can not start Windows Sockets\n");
806 win32_chdir(const char *dir)
808 #if USE_WIN32_UNICODE
809 WCHAR szBuf[MAX_PATH_UNICODE];
810 UTF8_2_wchar(szBuf, dir, MAX_PATH_UNICODE);
812 if (0 == SetCurrentDirectoryW(szBuf)) {
813 errno = b_errno_win32;
817 if (0 == SetCurrentDirectoryA(dir)) {
818 errno = b_errno_win32;
827 win32_mkdir(const char *dir)
829 #if USE_WIN32_UNICODE
830 WCHAR szBuf[MAX_PATH_UNICODE];
831 UTF8_2_wchar(szBuf, dir, MAX_PATH_UNICODE);
833 return _wmkdir(szBuf);
841 win32_getcwd(char *buf, int maxlen)
843 #if USE_WIN32_UNICODE
844 WCHAR szBuf[MAX_PATH_UNICODE];
845 int n = GetCurrentDirectoryW(maxlen, szBuf);
846 n = wchar_2_UTF8 (buf, szBuf, maxlen)-1;
848 int n = GetCurrentDirectory(maxlen, buf);
851 if (n == 0 || n > maxlen) return NULL;
853 if (n+1 > maxlen) return NULL;
861 #include "mswinver.h"
863 char WIN_VERSION_LONG[64];
864 char WIN_VERSION[32];
871 static winver INIT; // cause constructor to be called before main()
878 const char *version = "";
879 const char *platform = "";
880 OSVERSIONINFO osvinfo;
881 osvinfo.dwOSVersionInfoSize = sizeof(osvinfo);
883 // Get the current OS version
884 if (!GetVersionEx(&osvinfo)) {
886 platform = "Unknown";
889 switch (_mkversion(osvinfo.dwPlatformId, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion))
891 case MS_WINDOWS_95: (version = "Windows 95"); break;
892 case MS_WINDOWS_98: (version = "Windows 98"); break;
893 case MS_WINDOWS_ME: (version = "Windows ME"); break;
894 case MS_WINDOWS_NT4:(version = "Windows NT 4.0"); platform = "NT"; break;
895 case MS_WINDOWS_2K: (version = "Windows 2000");platform = "NT"; break;
896 case MS_WINDOWS_XP: (version = "Windows XP");platform = "NT"; break;
897 case MS_WINDOWS_S2003: (version = "Windows Server 2003");platform = "NT"; break;
898 default: version = "Windows ??"; break;
901 bstrncpy(WIN_VERSION_LONG, version, sizeof(WIN_VERSION_LONG));
902 snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %d.%d.%d",
903 platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
906 HANDLE h = CreateFile("G:\\foobar", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
910 BPIPE *b = open_bpipe("ls -l", 10, "r");
912 while (!feof(b->rfd)) {
913 fgets(buf, sizeof(buf), b->rfd);
919 BOOL CreateChildProcess(VOID);
920 VOID WriteToPipe(VOID);
921 VOID ReadFromPipe(VOID);
922 VOID ErrorExit(LPTSTR);
923 VOID ErrMsg(LPTSTR, BOOL);
926 * Check for a quoted path, if an absolute path name is given and it contains
927 * spaces it will need to be quoted. i.e. "c:/Program Files/foo/bar.exe"
928 * CreateProcess() says the best way to ensure proper results with executables
929 * with spaces in path or filename is to quote the string.
932 getArgv0(const char *cmdline)
936 for (const char *cp = cmdline; *cp; cp++)
941 if (!inquote && isspace(*cp))
946 int len = cp - cmdline;
947 char *rval = (char *)malloc(len+1);
961 * OK, so it would seem CreateProcess only handles true executables:
962 * .com or .exe files.
963 * So test to see whether we're getting a .bat file and if so grab
964 * $COMSPEC value and pass batch file to it.
967 CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err)
969 PROCESS_INFORMATION piProcInfo;
970 STARTUPINFO siStartInfo;
971 BOOL bFuncRetn = FALSE;
973 // Set up members of the PROCESS_INFORMATION structure.
975 ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
977 // Set up members of the STARTUPINFO structure.
979 ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
980 siStartInfo.cb = sizeof(STARTUPINFO);
981 // setup new process to use supplied handles for stdin,stdout,stderr
982 // if supplied handles are not used the send a copy of our STD_HANDLE
984 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
986 if (in != INVALID_HANDLE_VALUE)
987 siStartInfo.hStdInput = in;
989 siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
991 if (out != INVALID_HANDLE_VALUE)
992 siStartInfo.hStdOutput = out;
994 siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
995 if (err != INVALID_HANDLE_VALUE)
996 siStartInfo.hStdError = err;
998 siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
999 // Create the child process.
1003 const char *comspec = getenv("COMSPEC");
1005 if (comspec == NULL) // should never happen
1006 return INVALID_HANDLE_VALUE;
1008 char *cmdLine = (char *)alloca(strlen(cmdline) + strlen(comspec) + 16);
1010 strcpy(exeFile, comspec);
1011 strcpy(cmdLine, comspec);
1012 strcat(cmdLine, " /c ");
1013 strcat(cmdLine, cmdline);
1015 // try to execute program
1016 bFuncRetn = CreateProcess(exeFile,
1017 cmdLine, // command line
1018 NULL, // process security attributes
1019 NULL, // primary thread security attributes
1020 TRUE, // handles are inherited
1021 0, // creation flags
1022 NULL, // use parent's environment
1023 NULL, // use parent's current directory
1024 &siStartInfo, // STARTUPINFO pointer
1025 &piProcInfo); // receives PROCESS_INFORMATION
1027 if (bFuncRetn == 0) {
1028 ErrorExit("CreateProcess failed\n");
1029 const char *err = errorString();
1030 d_msg(__FILE__, __LINE__, 99,
1031 "CreateProcess(%s, %s, ...)=%s\n", exeFile, cmdLine, err);
1032 LocalFree((void *)err);
1033 return INVALID_HANDLE_VALUE;
1035 // we don't need a handle on the process primary thread so we close
1037 CloseHandle(piProcInfo.hThread);
1039 return piProcInfo.hProcess;
1044 ErrorExit (LPTSTR lpszMessage)
1046 d_msg(__FILE__, __LINE__, 0, "%s", lpszMessage);
1051 typedef struct s_bpipe {
1053 time_t worker_stime;
1062 CloseIfValid(HANDLE handle)
1064 if (handle != INVALID_HANDLE_VALUE)
1065 CloseHandle(handle);
1070 open_bpipe(char *prog, int wait, const char *mode)
1072 HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
1073 hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup,
1076 SECURITY_ATTRIBUTES saAttr;
1080 hChildStdinRd = hChildStdinWr = hChildStdinWrDup =
1081 hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup =
1082 hInputFile = INVALID_HANDLE_VALUE;
1084 BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
1085 memset((void *)bpipe, 0, sizeof(BPIPE));
1087 int mode_read = (mode[0] == 'r');
1088 int mode_write = (mode[0] == 'w' || mode[1] == 'w');
1091 // Set the bInheritHandle flag so pipe handles are inherited.
1093 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1094 saAttr.bInheritHandle = TRUE;
1095 saAttr.lpSecurityDescriptor = NULL;
1099 // Create a pipe for the child process's STDOUT.
1100 if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
1101 ErrorExit("Stdout pipe creation failed\n");
1104 // Create noninheritable read handle and close the inheritable read
1107 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
1108 GetCurrentProcess(), &hChildStdoutRdDup , 0,
1110 DUPLICATE_SAME_ACCESS);
1112 ErrorExit("DuplicateHandle failed");
1116 CloseHandle(hChildStdoutRd);
1117 hChildStdoutRd = INVALID_HANDLE_VALUE;
1122 // Create a pipe for the child process's STDIN.
1124 if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
1125 ErrorExit("Stdin pipe creation failed\n");
1129 // Duplicate the write handle to the pipe so it is not inherited.
1130 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
1131 GetCurrentProcess(), &hChildStdinWrDup,
1133 FALSE, // not inherited
1134 DUPLICATE_SAME_ACCESS);
1136 ErrorExit("DuplicateHandle failed");
1140 CloseHandle(hChildStdinWr);
1141 hChildStdinWr = INVALID_HANDLE_VALUE;
1143 // spawn program with redirected handles as appropriate
1144 bpipe->worker_pid = (pid_t)
1145 CreateChildProcess(prog, // commandline
1146 hChildStdinRd, // stdin HANDLE
1147 hChildStdoutWr, // stdout HANDLE
1148 hChildStdoutWr); // stderr HANDLE
1150 if ((HANDLE) bpipe->worker_pid == INVALID_HANDLE_VALUE)
1154 bpipe->worker_stime = time(NULL);
1157 CloseHandle(hChildStdoutWr); // close our write side so when
1158 // process terminates we can
1160 // ugly but convert WIN32 HANDLE to FILE*
1161 int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
1163 bpipe->rfd = _fdopen(rfd, "r");
1167 CloseHandle(hChildStdinRd); // close our read side so as not
1168 // to interfre with child's copy
1169 // ugly but convert WIN32 HANDLE to FILE*
1170 int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
1172 bpipe->wfd = _fdopen(wfd, "w");
1177 bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
1184 CloseIfValid(hChildStdoutRd);
1185 CloseIfValid(hChildStdoutRdDup);
1186 CloseIfValid(hChildStdinWr);
1187 CloseIfValid(hChildStdinWrDup);
1189 free((void *) bpipe);
1190 errno = b_errno_win32; /* do GetLastError() for error code */
1197 kill(int pid, int signal)
1200 if (!TerminateProcess((HANDLE)pid, (UINT) signal)) {
1202 errno = b_errno_win32;
1204 CloseHandle((HANDLE)pid);
1211 close_bpipe(BPIPE *bpipe)
1214 int32_t remaining_wait = bpipe->wait;
1216 if (remaining_wait == 0) { /* wait indefinitely */
1217 remaining_wait = INT32_MAX;
1221 if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode)) {
1222 const char *err = errorString();
1223 rval = b_errno_win32;
1224 d_msg(__FILE__, __LINE__, 0,
1225 "GetExitCode error %s\n", err);
1226 LocalFree((void *)err);
1229 if (exitCode == STILL_ACTIVE) {
1230 if (remaining_wait <= 0) {
1231 rval = ETIME; /* timed out */
1234 bmicrosleep(1, 0); /* wait one second */
1236 } else if (exitCode != 0) {
1237 /* Truncate exit code as it doesn't seem to be correct */
1238 rval = (exitCode & 0xFF) | b_errno_exit;
1241 break; /* Shouldn't get here */
1245 if (bpipe->timer_id) {
1246 stop_child_timer(bpipe->timer_id);
1248 if (bpipe->rfd) fclose(bpipe->rfd);
1249 if (bpipe->wfd) fclose(bpipe->wfd);
1250 free((void *)bpipe);
1255 close_wpipe(BPIPE *bpipe)
1261 if (fclose(bpipe->wfd) != 0) {
1269 #include "findlib/find.h"
1272 utime(const char *fname, struct utimbuf *times)
1277 cygwin_conv_to_win32_path(fname, tmpbuf);
1279 cvt_utime_to_ftime(times->actime, acc);
1280 cvt_utime_to_ftime(times->modtime, mod);
1283 #if USE_WIN32_UNICODE
1284 WCHAR szBuf[MAX_PATH_UNICODE];
1285 UTF8_2_wchar(szBuf, tmpbuf, MAX_PATH_UNICODE);
1287 HANDLE h = CreateFileW(szBuf,
1288 FILE_WRITE_ATTRIBUTES,
1295 HANDLE h = CreateFile(tmpbuf,
1296 FILE_WRITE_ATTRIBUTES,
1306 if (h == INVALID_HANDLE_VALUE) {
1307 const char *err = errorString();
1308 d_msg(__FILE__, __LINE__, 99,
1309 "Cannot open file \"%s\" for utime(): ERR=%s", tmpbuf, err);
1310 LocalFree((void *)err);
1311 errno = b_errno_win32;
1315 int rval = SetFileTime(h, NULL, &acc, &mod) ? 0 : -1;
1318 errno = b_errno_win32;
1323 #if USE_WIN32_COMPAT_IO
1326 open(const char *file, int flags, int mode)
1328 #if USE_WIN32_UNICODE
1329 WCHAR szBuf[MAX_PATH_UNICODE];
1330 UTF8_2_wchar(szBuf, file, MAX_PATH_UNICODE);
1332 return _wopen(szBuf, flags|_O_BINARY, mode);
1334 return _open(file, flags|_O_BINARY, mode);
1339 * Note, this works only for a file. If you want
1340 * to close a socket, use closesocket().
1341 * Bacula has been modified in src/lib/bnet.c
1342 * to use closesocket().
1350 #ifndef HAVE_WXCONSOLE
1352 read(int fd, void *buf, ssize_t len)
1354 return _read(fd, buf, (size_t)len);
1358 write(int fd, const void *buf, ssize_t len)
1360 return _write(fd, buf, (size_t)len);
1365 lseek(int fd, off_t offset, int whence)
1367 return _lseeki64(fd, offset, whence);
1371 dup2(int fd1, int fd2)
1373 return _dup2(fd1, fd2);
1377 open(const char *file, int flags, int mode)
1380 DWORD shareMode = 0;
1384 const char *remap = file;
1386 if (flags & O_WRONLY) access = GENERIC_WRITE;
1387 else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
1388 else access = GENERIC_READ;
1390 if (flags & O_CREAT) create = CREATE_NEW;
1391 else create = OPEN_EXISTING;
1393 if (flags & O_TRUNC) create = TRUNCATE_EXISTING;
1395 if (!(flags & O_EXCL))
1396 shareMode = FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE;
1398 if (flags & O_APPEND) {
1399 printf("open...APPEND not implemented yet.");
1404 #if USE_WIN32_UNICODE
1405 WCHAR szBuf[MAX_PATH_UNICODE];
1406 UTF8_2_wchar(szBuf, file, MAX_PATH_UNICODE);
1408 foo = CreateFileW(szBuf, access, shareMode, NULL, create, msflags, NULL);
1410 foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
1414 if (INVALID_HANDLE_VALUE == foo) {
1415 errno = b_errno_win32;
1426 if (!CloseHandle((HANDLE)fd)) {
1427 errno = b_errno_win32;
1435 write(int fd, const void *data, ssize_t len)
1439 status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
1440 if (status) return bwrite;
1441 errno = b_errno_win32;
1447 read(int fd, void *data, ssize_t len)
1452 status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
1453 if (status) return bread;
1454 errno = b_errno_win32;
1459 lseek(int fd, off_t offset, int whence)
1465 method = FILE_BEGIN;
1468 method = FILE_CURRENT;
1478 if ((val=SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method)) == INVALID_SET_FILE_POINTER) {
1479 errno = b_errno_win32;
1482 /* ***FIXME*** I doubt this works right */
1499 /* syslog function, added by Nicolas Boichat */