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-2005 Kern Sibbald
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
33 #include "../../lib/winapi.h"
35 #define b_errno_win32 (1<<29)
37 #define USE_WIN32_COMPAT_IO 1
39 extern void d_msg(const char *file, int line, int level, const char *fmt,...);
40 extern DWORD g_platform_id;
42 // from MicroSoft SDK (KES) is the diff between Jan 1 1601 and Jan 1 1970
44 #define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000UL //Not sure it works
46 #define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000I64
49 #define WIN32_FILETIME_SCALE 10000000 // 100ns/second
52 cygwin_conv_to_win32_path(const char *name, char *win32_name)
54 const char *fname = name;
56 /* Check for Unix separator and convert to Win32 */
58 *win32_name++ = '\\'; /* convert char */
59 /* If Win32 separated that is "quoted", remove quote */
60 } else if (*name == '\\' && name[1] == '\\') {
62 name++; /* skip first \ */
64 *win32_name++ = *name; /* copy character */
68 /* Strip any trailing slash, if we stored something */
69 if (*fname != 0 && win32_name[-1] == '\\') {
77 wchar_2_UTF8(char *pszUTF, const WCHAR *pszUCS, int cchChar)
79 /* the return value is the number of bytes written to the buffer.
80 The number includes the byte for the null terminator. */
82 if (p_WideCharToMultiByte)
83 return p_WideCharToMultiByte(CP_UTF8,0,pszUCS,-1,pszUTF,cchChar,NULL,NULL);
89 UTF8_2_wchar(WCHAR *pszUCS, const char *pszUTF, int cchWideChar)
91 /* the return value is the number of wide characters written to the buffer. */
92 /* convert null terminated string from utf-8 to ucs2*/
94 if (p_MultiByteToWideChar)
95 return p_MultiByteToWideChar(CP_UTF8, 0, pszUTF, -1, pszUCS,cchWideChar);
102 wchar_win32_path(const char *name, WCHAR *win32_name)
104 const char *fname = name;
106 /* Check for Unix separator and convert to Win32 */
108 *win32_name++ = '\\'; /* convert char */
109 /* If Win32 separated that is "quoted", remove quote */
110 } else if (*name == '\\' && name[1] == '\\') {
111 *win32_name++ = '\\';
112 name++; /* skip first \ */
114 *win32_name++ = *name; /* copy character */
118 /* Strip any trailing slash, if we stored something */
119 if (*fname != 0 && win32_name[-1] == '\\') {
131 int chmod(const char *, mode_t)
136 int chown(const char *k, uid_t, gid_t)
141 int lchown(const char *k, uid_t, gid_t)
147 bool fstype(const char *fname, char *fs, int fslen)
149 return true; /* accept anything */
161 srandom(unsigned int seed)
165 // /////////////////////////////////////////////////////////////////
166 // convert from Windows concept of time to Unix concept of time
167 // /////////////////////////////////////////////////////////////////
169 cvt_utime_to_ftime(const time_t &time, FILETIME &wintime)
171 uint64_t mstime = time;
172 mstime *= WIN32_FILETIME_SCALE;
173 mstime += WIN32_FILETIME_ADJUST;
176 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffUL);
178 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffI64);
180 wintime.dwHighDateTime = (DWORD) ((mstime>>32)& 0xffffffffUL);
184 cvt_ftime_to_utime(const FILETIME &time)
186 uint64_t mstime = time.dwHighDateTime;
188 mstime |= time.dwLowDateTime;
190 mstime -= WIN32_FILETIME_ADJUST;
191 mstime /= WIN32_FILETIME_SCALE; // convert to seconds.
193 return (time_t) (mstime & 0xffffffff);
201 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
202 FORMAT_MESSAGE_FROM_SYSTEM |
203 FORMAT_MESSAGE_IGNORE_INSERTS,
206 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default lang
211 return (const char *) lpMsgBuf;
217 statDir(const char *file, struct stat *sb)
219 WIN32_FIND_DATAW info_w; // window's file info
220 WIN32_FIND_DATA info_a; // window's file info
222 // cache some common vars to make code more transparent
223 DWORD* pdwFileAttributes;
224 DWORD* pnFileSizeHigh;
225 DWORD* pnFileSizeLow;
226 FILETIME* pftLastAccessTime;
227 FILETIME* pftLastWriteTime;
228 FILETIME* pftCreationTime;
230 if (file[1] == ':' && file[2] == 0) {
231 d_msg(__FILE__, __LINE__, 99, "faking ROOT attrs(%s).\n", file);
232 sb->st_mode = S_IFDIR;
233 sb->st_mode |= S_IREAD|S_IEXEC|S_IWRITE;
240 HANDLE h = INVALID_HANDLE_VALUE;
242 // use unicode or ascii
243 if (p_FindFirstFileW) {
244 WCHAR szBuf[MAX_PATH_UNICODE];
245 UTF8_2_wchar(szBuf, file, MAX_PATH_UNICODE);
247 h = p_FindFirstFileW(szBuf, &info_w);
249 pdwFileAttributes = &info_w.dwFileAttributes;
250 pnFileSizeHigh = &info_w.nFileSizeHigh;
251 pnFileSizeLow = &info_w.nFileSizeLow;
252 pftLastAccessTime = &info_w.ftLastAccessTime;
253 pftLastWriteTime = &info_w.ftLastWriteTime;
254 pftCreationTime = &info_w.ftCreationTime;
256 else if (p_FindFirstFileA) {
257 h = p_FindFirstFileA(file, &info_a);
259 pdwFileAttributes = &info_a.dwFileAttributes;
260 pnFileSizeHigh = &info_a.nFileSizeHigh;
261 pnFileSizeLow = &info_a.nFileSizeLow;
262 pftLastAccessTime = &info_a.ftLastAccessTime;
263 pftLastWriteTime = &info_a.ftLastWriteTime;
264 pftCreationTime = &info_a.ftCreationTime;
267 if (h == INVALID_HANDLE_VALUE) {
268 const char *err = errorString();
269 d_msg(__FILE__, __LINE__, 99, "FindFirstFile(%s):%s\n", file, err);
270 LocalFree((void *)err);
271 errno = b_errno_win32;
275 sb->st_mode = 0777; /* start with everything */
276 if (*pdwFileAttributes & FILE_ATTRIBUTE_READONLY)
277 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
278 if (*pdwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
279 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
280 if (*pdwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
281 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
282 sb->st_mode |= S_IFDIR;
284 sb->st_size = *pnFileSizeHigh;
286 sb->st_size |= *pnFileSizeLow;
287 sb->st_blksize = 4096;
288 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
290 sb->st_atime = cvt_ftime_to_utime(*pftLastAccessTime);
291 sb->st_mtime = cvt_ftime_to_utime(*pftLastWriteTime);
292 sb->st_ctime = cvt_ftime_to_utime(*pftCreationTime);
299 stat2(const char *file, struct stat *sb)
301 BY_HANDLE_FILE_INFORMATION info;
305 cygwin_conv_to_win32_path(file, tmpbuf);
309 if (p_GetFileAttributesW) {
310 WCHAR szBuf[MAX_PATH_UNICODE];
311 UTF8_2_wchar(szBuf, tmpbuf, MAX_PATH_UNICODE);
313 attr = p_GetFileAttributesW(szBuf);
315 else if (p_GetFileAttributesA) {
316 attr = p_GetFileAttributesA(tmpbuf);
320 const char *err = errorString();
321 d_msg(__FILE__, __LINE__, 99,
322 "GetFileAttrubtes(%s): %s\n", tmpbuf, err);
323 LocalFree((void *)err);
324 errno = b_errno_win32;
328 if (attr & FILE_ATTRIBUTE_DIRECTORY)
329 return statDir(tmpbuf, sb);
331 h = CreateFile(tmpbuf, GENERIC_READ,
332 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
334 if (h == INVALID_HANDLE_VALUE) {
335 const char *err = errorString();
336 d_msg(__FILE__, __LINE__, 99,
337 "Cannot open file for stat (%s):%s\n", tmpbuf, err);
338 LocalFree((void *)err);
340 errno = b_errno_win32;
344 if (!GetFileInformationByHandle(h, &info)) {
345 const char *err = errorString();
346 d_msg(__FILE__, __LINE__, 99,
347 "GetfileInformationByHandle(%s): %s\n", tmpbuf, err);
348 LocalFree((void *)err);
350 errno = b_errno_win32;
354 sb->st_dev = info.dwVolumeSerialNumber;
355 sb->st_ino = info.nFileIndexHigh;
357 sb->st_ino |= info.nFileIndexLow;
358 sb->st_nlink = (short)info.nNumberOfLinks;
359 if (sb->st_nlink > 1) {
360 d_msg(__FILE__, __LINE__, 99, "st_nlink=%d\n", sb->st_nlink);
363 sb->st_mode = 0777; /* start with everything */
364 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
365 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
366 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
367 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
368 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
369 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
370 sb->st_mode |= S_IFREG;
372 sb->st_size = info.nFileSizeHigh;
374 sb->st_size |= info.nFileSizeLow;
375 sb->st_blksize = 4096;
376 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
377 sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
378 sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
379 sb->st_ctime = cvt_ftime_to_utime(info.ftCreationTime);
387 stat(const char *file, struct stat *sb)
389 WIN32_FILE_ATTRIBUTE_DATA data;
393 memset(sb, 0, sizeof(*sb));
395 if (g_platform_id == VER_PLATFORM_WIN32_WINDOWS)
396 return stat2(file, sb);
398 // otherwise we're on NT
406 wchar_win32_path(file, buf+4);
408 if (!GetFileAttributesExW((WCHAR *)buf, GetFileExInfoStandard, &data))
409 return stat2(file, sb);
412 if (p_GetFileAttributesExW) {
413 WCHAR buf[MAX_PATH_UNICODE];
414 UTF8_2_wchar(buf, file, MAX_PATH_UNICODE);
415 if (!p_GetFileAttributesExW(buf, GetFileExInfoStandard, &data))
416 return stat2(file, sb);
417 } else if (p_GetFileAttributesExA) {
418 if (!p_GetFileAttributesExA(file, GetFileExInfoStandard, &data))
419 return stat2(file, sb);
422 return stat2(file, sb);
426 sb->st_mode = 0777; /* start with everything */
427 if (data.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
428 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
429 if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
430 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
431 if (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
432 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
434 if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
435 sb->st_mode |= S_IFDIR;
437 sb->st_mode |= S_IFREG;
440 sb->st_size = data.nFileSizeHigh;
442 sb->st_size |= data.nFileSizeLow;
443 sb->st_blksize = 4096;
444 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
445 sb->st_atime = cvt_ftime_to_utime(data.ftLastAccessTime);
446 sb->st_mtime = cvt_ftime_to_utime(data.ftLastWriteTime);
447 sb->st_ctime = cvt_ftime_to_utime(data.ftCreationTime);
454 lstat(const char *file, struct stat *sb)
456 return stat(file, sb);
472 execvp(const char *, char *[]) {
493 waitpid(int, int*, int)
500 readlink(const char *, char *, int)
509 strcasecmp(const char *s1, const char *s2)
511 register int ch1, ch2;
514 return 0; /* strings are equal if same object. */
525 } while (ch1 != 0 && tolower(ch1) == tolower(ch2));
532 strncasecmp(const char *s1, const char *s2, int len)
534 register int ch1, ch2;
537 return 0; /* strings are equal if same object. */
548 if (ch1 == 0 || tolower(ch1) != tolower(ch2)) break;
555 gettimeofday(struct timeval *tv, struct timezone *)
565 if (!SystemTimeToFileTime(&now, &tmp)) {
566 errno = b_errno_win32;
570 int64_t _100nsec = tmp.dwHighDateTime;
572 _100nsec |= tmp.dwLowDateTime;
573 _100nsec -= WIN32_FILETIME_ADJUST;
575 tv->tv_sec =(long) (_100nsec / 10000000);
576 tv->tv_usec = (long) ((_100nsec % 10000000)/10);
582 syslog(int type, const char *fmt, const char *msg)
584 /*#ifndef HAVE_CONSOLE
585 MessageBox(NULL, msg, "Bacula", MB_OK);
602 // implement opendir/readdir/closedir on top of window's API
606 WIN32_FIND_DATA data_a; // window's file info (ansii version)
607 WIN32_FIND_DATAW data_w; // window's file info (wchar version)
608 const char *spec; // the directory we're traversing
609 HANDLE dirh; // the search handle
610 BOOL valid_a; // the info in data_a field is valid
611 BOOL valid_w; // the info in data_w field is valid
612 UINT32 offset; // pseudo offset for d_off
616 opendir(const char *path)
618 int max_len = strlen(path) + 16;
625 rval = (_dir *)malloc(sizeof(_dir));
626 memset (rval, 0, sizeof (_dir));
627 if (rval == NULL) return NULL;
628 char *tspec = (char *)malloc(max_len);
629 if (tspec == NULL) return NULL;
631 if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS) {
632 // allow path to be 32767 bytes
638 cygwin_conv_to_win32_path(path, tspec+4);
640 cygwin_conv_to_win32_path(path, tspec);
643 strncat(tspec, "\\*", max_len);
647 if (p_FindFirstFileW) {
648 WCHAR wcBuf[MAX_PATH_UNICODE];
649 UTF8_2_wchar(wcBuf,rval->spec, MAX_PATH_UNICODE);
650 rval->dirh = p_FindFirstFileW(wcBuf, &rval->data_w);
652 if (rval->dirh != INVALID_HANDLE_VALUE)
654 } else if (p_FindFirstFileA) {
655 rval->dirh = p_FindFirstFileA(rval->spec, &rval->data_a);
657 if (rval->dirh != INVALID_HANDLE_VALUE)
662 d_msg(__FILE__, __LINE__,
663 99, "opendir(%s)\n\tspec=%s,\n\tFindFirstFile returns %d\n",
664 path, rval->spec, rval->dirh);
667 if (rval->dirh == INVALID_HANDLE_VALUE)
671 d_msg(__FILE__, __LINE__,
672 99, "\tFirstFile=%s\n", rval->data_w.cFileName);
675 d_msg(__FILE__, __LINE__,
676 99, "\tFirstFile=%s\n", rval->data_a.cFileName);
681 free((void *)rval->spec);
683 errno = b_errno_win32;
690 _dir *dp = (_dir *)dirp;
692 free((void *)dp->spec);
698 typedef struct _WIN32_FIND_DATA {
699 DWORD dwFileAttributes;
700 FILETIME ftCreationTime;
701 FILETIME ftLastAccessTime;
702 FILETIME ftLastWriteTime;
707 TCHAR cFileName[MAX_PATH];
708 TCHAR cAlternateFileName[14];
709 } WIN32_FIND_DATA, *PWIN32_FIND_DATA;
713 copyin(struct dirent &dp, const char *fname)
717 char *cp = dp.d_name;
727 readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
729 _dir *dp = (_dir *)dirp;
730 if (dp->valid_w || dp->valid_a) {
731 entry->d_off = dp->offset;
735 char szBuf[MAX_PATH_UTF8];
736 wchar_2_UTF8(szBuf,dp->data_w.cFileName);
737 dp->offset += copyin(*entry, szBuf);
738 } else if (dp->valid_a) { // copy ansi (only 1 will be valid)
739 dp->offset += copyin(*entry, dp->data_a.cFileName);
742 *result = entry; /* return entry address */
743 d_msg(__FILE__, __LINE__,
744 99, "readdir_r(%p, { d_name=\"%s\", d_reclen=%d, d_off=%d\n",
745 dirp, entry->d_name, entry->d_reclen, entry->d_off);
747 // d_msg(__FILE__, __LINE__, 99, "readdir_r !valid\n");
748 errno = b_errno_win32;
752 // get next file, try unicode first
754 dp->valid_w = p_FindNextFileW(dp->dirh, &dp->data_w);
755 else if (p_FindNextFileA)
756 dp->valid_a = p_FindNextFileA(dp->dirh, &dp->data_a);
766 * Dotted IP address to network address
772 inet_aton(const char *a, struct in_addr *inp)
775 uint32_t acc = 0, tmp = 0;
778 if (!isdigit(*cp)) { /* first char must be digit */
779 return 0; /* error */
783 tmp = (tmp * 10) + (*cp -'0');
784 } else if (*cp == '.' || *cp == 0) {
786 return 0; /* error */
788 acc = (acc << 8) + tmp;
792 return 0; /* error */
794 } while (*cp++ != 0);
795 if (dotc != 4) { /* want 3 .'s plus EOS */
796 return 0; /* error */
798 inp->s_addr = htonl(acc); /* store addr in network format */
803 nanosleep(const struct timespec *req, struct timespec *rem)
806 rem->tv_sec = rem->tv_nsec = 0;
807 Sleep((req->tv_sec * 1000) + (req->tv_nsec/100000));
812 init_signals(void terminate(int sig))
818 init_stack_dump(void)
825 pathconf(const char *path, int name)
829 if (strncmp(path, "\\\\?\\", 4) == 0)
841 WORD wVersionRequested = MAKEWORD( 1, 1);
844 int err = WSAStartup(wVersionRequested, &wsaData);
848 printf("Can not start Windows Sockets\n");
858 win32_chdir(const char *dir)
860 if (p_SetCurrentDirectoryW) {
861 WCHAR szBuf[MAX_PATH_UNICODE];
862 UTF8_2_wchar(szBuf, dir, MAX_PATH_UNICODE);
864 if (0 == p_SetCurrentDirectoryW(szBuf)) {
865 errno = b_errno_win32;
869 else if (p_SetCurrentDirectoryA) {
870 if (0 == p_SetCurrentDirectoryA(dir)) {
871 errno = b_errno_win32;
881 win32_mkdir(const char *dir)
884 WCHAR szBuf[MAX_PATH_UNICODE];
885 UTF8_2_wchar(szBuf, dir, MAX_PATH_UNICODE);
886 return p_wmkdir(szBuf);
894 win32_getcwd(char *buf, int maxlen)
898 if (p_GetCurrentDirectoryW) {
899 WCHAR szBuf[MAX_PATH_UNICODE];
900 n = p_GetCurrentDirectoryW(maxlen, szBuf);
901 n = wchar_2_UTF8 (buf, szBuf, maxlen)-1;
902 } else if (p_GetCurrentDirectoryA)
903 n = p_GetCurrentDirectoryA(maxlen, buf);
905 if (n == 0 || n > maxlen) return NULL;
907 if (n+1 > maxlen) return NULL;
915 #include "mswinver.h"
917 char WIN_VERSION_LONG[64];
918 char WIN_VERSION[32];
925 static winver INIT; // cause constructor to be called before main()
932 const char *version = "";
933 const char *platform = "";
934 OSVERSIONINFO osvinfo;
935 osvinfo.dwOSVersionInfoSize = sizeof(osvinfo);
937 // Get the current OS version
938 if (!GetVersionEx(&osvinfo)) {
940 platform = "Unknown";
943 switch (_mkversion(osvinfo.dwPlatformId, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion))
945 case MS_WINDOWS_95: (version = "Windows 95"); break;
946 case MS_WINDOWS_98: (version = "Windows 98"); break;
947 case MS_WINDOWS_ME: (version = "Windows ME"); break;
948 case MS_WINDOWS_NT4:(version = "Windows NT 4.0"); platform = "NT"; break;
949 case MS_WINDOWS_2K: (version = "Windows 2000");platform = "NT"; break;
950 case MS_WINDOWS_XP: (version = "Windows XP");platform = "NT"; break;
951 case MS_WINDOWS_S2003: (version = "Windows Server 2003");platform = "NT"; break;
952 default: version = "Windows ??"; break;
955 bstrncpy(WIN_VERSION_LONG, version, sizeof(WIN_VERSION_LONG));
956 snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %d.%d.%d",
957 platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
960 HANDLE h = CreateFile("G:\\foobar", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
964 BPIPE *b = open_bpipe("ls -l", 10, "r");
966 while (!feof(b->rfd)) {
967 fgets(buf, sizeof(buf), b->rfd);
973 BOOL CreateChildProcess(VOID);
974 VOID WriteToPipe(VOID);
975 VOID ReadFromPipe(VOID);
976 VOID ErrorExit(LPTSTR);
977 VOID ErrMsg(LPTSTR, BOOL);
980 * Check for a quoted path, if an absolute path name is given and it contains
981 * spaces it will need to be quoted. i.e. "c:/Program Files/foo/bar.exe"
982 * CreateProcess() says the best way to ensure proper results with executables
983 * with spaces in path or filename is to quote the string.
986 getArgv0(const char *cmdline)
990 for (const char *cp = cmdline; *cp; cp++)
995 if (!inquote && isspace(*cp))
1000 int len = cp - cmdline;
1001 char *rval = (char *)malloc(len+1);
1015 * OK, so it would seem CreateProcess only handles true executables:
1016 * .com or .exe files.
1017 * So test to see whether we're getting a .bat file and if so grab
1018 * $COMSPEC value and pass batch file to it.
1021 CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err)
1023 PROCESS_INFORMATION piProcInfo;
1024 STARTUPINFO siStartInfo;
1025 BOOL bFuncRetn = FALSE;
1027 // Set up members of the PROCESS_INFORMATION structure.
1029 ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
1031 // Set up members of the STARTUPINFO structure.
1033 ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
1034 siStartInfo.cb = sizeof(STARTUPINFO);
1035 // setup new process to use supplied handles for stdin,stdout,stderr
1036 // if supplied handles are not used the send a copy of our STD_HANDLE
1038 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
1040 if (in != INVALID_HANDLE_VALUE)
1041 siStartInfo.hStdInput = in;
1043 siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1045 if (out != INVALID_HANDLE_VALUE)
1046 siStartInfo.hStdOutput = out;
1048 siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1049 if (err != INVALID_HANDLE_VALUE)
1050 siStartInfo.hStdError = err;
1052 siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1053 // Create the child process.
1057 const char *comspec = getenv("COMSPEC");
1059 if (comspec == NULL) // should never happen
1060 return INVALID_HANDLE_VALUE;
1062 char *cmdLine = (char *)alloca(strlen(cmdline) + strlen(comspec) + 16);
1064 strcpy(exeFile, comspec);
1065 strcpy(cmdLine, comspec);
1066 strcat(cmdLine, " /c ");
1067 strcat(cmdLine, cmdline);
1069 // try to execute program
1070 bFuncRetn = CreateProcess(exeFile,
1071 cmdLine, // command line
1072 NULL, // process security attributes
1073 NULL, // primary thread security attributes
1074 TRUE, // handles are inherited
1075 0, // creation flags
1076 NULL, // use parent's environment
1077 NULL, // use parent's current directory
1078 &siStartInfo, // STARTUPINFO pointer
1079 &piProcInfo); // receives PROCESS_INFORMATION
1081 if (bFuncRetn == 0) {
1082 ErrorExit("CreateProcess failed\n");
1083 const char *err = errorString();
1084 d_msg(__FILE__, __LINE__, 99,
1085 "CreateProcess(%s, %s, ...)=%s\n", exeFile, cmdLine, err);
1086 LocalFree((void *)err);
1087 return INVALID_HANDLE_VALUE;
1089 // we don't need a handle on the process primary thread so we close
1091 CloseHandle(piProcInfo.hThread);
1093 return piProcInfo.hProcess;
1098 ErrorExit (LPTSTR lpszMessage)
1100 d_msg(__FILE__, __LINE__, 0, "%s", lpszMessage);
1105 typedef struct s_bpipe {
1107 time_t worker_stime;
1116 CloseIfValid(HANDLE handle)
1118 if (handle != INVALID_HANDLE_VALUE)
1119 CloseHandle(handle);
1124 open_bpipe(char *prog, int wait, const char *mode)
1126 HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
1127 hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup,
1130 SECURITY_ATTRIBUTES saAttr;
1134 hChildStdinRd = hChildStdinWr = hChildStdinWrDup =
1135 hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup =
1136 hInputFile = INVALID_HANDLE_VALUE;
1138 BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
1139 memset((void *)bpipe, 0, sizeof(BPIPE));
1141 int mode_read = (mode[0] == 'r');
1142 int mode_write = (mode[0] == 'w' || mode[1] == 'w');
1145 // Set the bInheritHandle flag so pipe handles are inherited.
1147 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1148 saAttr.bInheritHandle = TRUE;
1149 saAttr.lpSecurityDescriptor = NULL;
1153 // Create a pipe for the child process's STDOUT.
1154 if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
1155 ErrorExit("Stdout pipe creation failed\n");
1158 // Create noninheritable read handle and close the inheritable read
1161 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
1162 GetCurrentProcess(), &hChildStdoutRdDup , 0,
1164 DUPLICATE_SAME_ACCESS);
1166 ErrorExit("DuplicateHandle failed");
1170 CloseHandle(hChildStdoutRd);
1171 hChildStdoutRd = INVALID_HANDLE_VALUE;
1176 // Create a pipe for the child process's STDIN.
1178 if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
1179 ErrorExit("Stdin pipe creation failed\n");
1183 // Duplicate the write handle to the pipe so it is not inherited.
1184 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
1185 GetCurrentProcess(), &hChildStdinWrDup,
1187 FALSE, // not inherited
1188 DUPLICATE_SAME_ACCESS);
1190 ErrorExit("DuplicateHandle failed");
1194 CloseHandle(hChildStdinWr);
1195 hChildStdinWr = INVALID_HANDLE_VALUE;
1197 // spawn program with redirected handles as appropriate
1198 bpipe->worker_pid = (pid_t)
1199 CreateChildProcess(prog, // commandline
1200 hChildStdinRd, // stdin HANDLE
1201 hChildStdoutWr, // stdout HANDLE
1202 hChildStdoutWr); // stderr HANDLE
1204 if ((HANDLE) bpipe->worker_pid == INVALID_HANDLE_VALUE)
1208 bpipe->worker_stime = time(NULL);
1211 CloseHandle(hChildStdoutWr); // close our write side so when
1212 // process terminates we can
1214 // ugly but convert WIN32 HANDLE to FILE*
1215 int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
1217 bpipe->rfd = _fdopen(rfd, "r");
1221 CloseHandle(hChildStdinRd); // close our read side so as not
1222 // to interfre with child's copy
1223 // ugly but convert WIN32 HANDLE to FILE*
1224 int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
1226 bpipe->wfd = _fdopen(wfd, "w");
1231 bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
1238 CloseIfValid(hChildStdoutRd);
1239 CloseIfValid(hChildStdoutRdDup);
1240 CloseIfValid(hChildStdinWr);
1241 CloseIfValid(hChildStdinWrDup);
1243 free((void *) bpipe);
1244 errno = b_errno_win32; /* do GetLastError() for error code */
1251 kill(int pid, int signal)
1254 if (!TerminateProcess((HANDLE)pid, (UINT) signal)) {
1256 errno = b_errno_win32;
1258 CloseHandle((HANDLE)pid);
1265 close_bpipe(BPIPE *bpipe)
1268 int32_t remaining_wait = bpipe->wait;
1270 if (remaining_wait == 0) { /* wait indefinitely */
1271 remaining_wait = INT32_MAX;
1275 if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode)) {
1276 const char *err = errorString();
1277 rval = b_errno_win32;
1278 d_msg(__FILE__, __LINE__, 0,
1279 "GetExitCode error %s\n", err);
1280 LocalFree((void *)err);
1283 if (exitCode == STILL_ACTIVE) {
1284 if (remaining_wait <= 0) {
1285 rval = ETIME; /* timed out */
1288 bmicrosleep(1, 0); /* wait one second */
1290 } else if (exitCode != 0) {
1291 /* Truncate exit code as it doesn't seem to be correct */
1292 rval = (exitCode & 0xFF) | b_errno_exit;
1295 break; /* Shouldn't get here */
1299 if (bpipe->timer_id) {
1300 stop_child_timer(bpipe->timer_id);
1302 if (bpipe->rfd) fclose(bpipe->rfd);
1303 if (bpipe->wfd) fclose(bpipe->wfd);
1304 free((void *)bpipe);
1309 close_wpipe(BPIPE *bpipe)
1315 if (fclose(bpipe->wfd) != 0) {
1323 #include "findlib/find.h"
1326 utime(const char *fname, struct utimbuf *times)
1331 cygwin_conv_to_win32_path(fname, tmpbuf);
1333 cvt_utime_to_ftime(times->actime, acc);
1334 cvt_utime_to_ftime(times->modtime, mod);
1336 HANDLE h = INVALID_HANDLE_VALUE;
1338 if (p_CreateFileW) {
1339 WCHAR szBuf[MAX_PATH_UNICODE];
1340 UTF8_2_wchar(szBuf, tmpbuf, MAX_PATH_UNICODE);
1342 h = p_CreateFileW(szBuf,
1343 FILE_WRITE_ATTRIBUTES,
1349 } else if (p_CreateFileA) {
1350 h = CreateFile(tmpbuf,
1351 FILE_WRITE_ATTRIBUTES,
1359 if (h == INVALID_HANDLE_VALUE) {
1360 const char *err = errorString();
1361 d_msg(__FILE__, __LINE__, 99,
1362 "Cannot open file \"%s\" for utime(): ERR=%s", tmpbuf, err);
1363 LocalFree((void *)err);
1364 errno = b_errno_win32;
1368 int rval = SetFileTime(h, NULL, &acc, &mod) ? 0 : -1;
1371 errno = b_errno_win32;
1376 #if USE_WIN32_COMPAT_IO
1379 unlink(const char *file)
1383 WCHAR szBuf[MAX_PATH_UNICODE];
1384 UTF8_2_wchar(szBuf, file, MAX_PATH_UNICODE);
1385 nRetCode = _wunlink(szBuf);
1387 nRetCode = _unlink(file);
1394 open(const char *file, int flags, int mode)
1397 WCHAR szBuf[MAX_PATH_UNICODE];
1398 UTF8_2_wchar(szBuf, file, MAX_PATH_UNICODE);
1400 return p_wopen(szBuf, flags|_O_BINARY, mode);
1403 return _open(file, flags|_O_BINARY, mode);
1407 * Note, this works only for a file. If you want
1408 * to close a socket, use closesocket().
1409 * Bacula has been modified in src/lib/bnet.c
1410 * to use closesocket().
1418 #ifndef HAVE_WXCONSOLE
1420 read(int fd, void *buf, ssize_t len)
1422 return _read(fd, buf, (size_t)len);
1426 write(int fd, const void *buf, ssize_t len)
1428 return _write(fd, buf, (size_t)len);
1434 lseek(int fd, off_t offset, int whence)
1436 return _lseeki64(fd, offset, whence);
1440 dup2(int fd1, int fd2)
1442 return _dup2(fd1, fd2);
1446 open(const char *file, int flags, int mode)
1449 DWORD shareMode = 0;
1452 HANDLE foo = INVALID_HANDLE_VALUE;
1453 const char *remap = file;
1455 if (flags & O_WRONLY) access = GENERIC_WRITE;
1456 else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
1457 else access = GENERIC_READ;
1459 if (flags & O_CREAT) create = CREATE_NEW;
1460 else create = OPEN_EXISTING;
1462 if (flags & O_TRUNC) create = TRUNCATE_EXISTING;
1464 if (!(flags & O_EXCL))
1465 shareMode = FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE;
1467 if (flags & O_APPEND) {
1468 printf("open...APPEND not implemented yet.");
1472 if (p_CreateFileW) {
1473 WCHAR szBuf[MAX_PATH_UNICODE];
1474 UTF8_2_wchar(szBuf, file, MAX_PATH_UNICODE);
1476 foo = p_CreateFileW(szBuf, access, shareMode, NULL, create, msflags, NULL);
1478 else if (p_CreateFileA)
1479 foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
1481 if (INVALID_HANDLE_VALUE == foo) {
1482 errno = b_errno_win32;
1493 if (!CloseHandle((HANDLE)fd)) {
1494 errno = b_errno_win32;
1502 write(int fd, const void *data, ssize_t len)
1506 status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
1507 if (status) return bwrite;
1508 errno = b_errno_win32;
1514 read(int fd, void *data, ssize_t len)
1519 status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
1520 if (status) return bread;
1521 errno = b_errno_win32;
1526 lseek(int fd, off_t offset, int whence)
1532 method = FILE_BEGIN;
1535 method = FILE_CURRENT;
1545 if ((val=SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method)) == INVALID_SET_FILE_POINTER) {
1546 errno = b_errno_win32;
1549 /* ***FIXME*** I doubt this works right */
1566 /* syslog function, added by Nicolas Boichat */