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-2006 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
12 // version 2 as amended with additional clauses defined in the
13 // file LICENSE in the main source directory.
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
18 // the file LICENSE for additional details.
20 // Author : Christopher S. Hull
21 // Created On : Sat Jan 31 15:55:00 2004
28 #define b_errno_win32 (1<<29)
30 #define MAX_PATHLENGTH 1024
32 /* UTF-8 to UCS2 path conversion is expensive,
33 so we cache the conversion. During backup the
34 conversion is called 3 times (lstat, attribs, open),
35 by using the cache this is reduced to 1 time */
37 static POOLMEM *g_pWin32ConvUTF8Cache = get_pool_memory (PM_FNAME);
38 static POOLMEM *g_pWin32ConvUCS2Cache = get_pool_memory (PM_FNAME);
39 static DWORD g_dwWin32ConvUTF8strlen = 0;
40 static pthread_mutex_t Win32Convmutex = PTHREAD_MUTEX_INITIALIZER;
42 static t_pVSSPathConvert g_pVSSPathConvert;
43 static t_pVSSPathConvertW g_pVSSPathConvertW;
45 void SetVSSPathConvert(t_pVSSPathConvert pPathConvert, t_pVSSPathConvertW pPathConvertW)
47 g_pVSSPathConvert = pPathConvert;
48 g_pVSSPathConvertW = pPathConvertW;
51 void Win32ConvCleanupCache()
53 if (g_pWin32ConvUTF8Cache) {
54 free_pool_memory(g_pWin32ConvUTF8Cache);
55 g_pWin32ConvUTF8Cache = NULL;
58 if (g_pWin32ConvUCS2Cache) {
59 free_pool_memory(g_pWin32ConvUCS2Cache);
60 g_pWin32ConvUCS2Cache = NULL;
63 g_dwWin32ConvUTF8strlen = 0;
67 /* to allow the usage of the original version in this file here */
71 //#define USE_WIN32_COMPAT_IO 1
72 #define USE_WIN32_32KPATHCONVERSION 1
74 extern DWORD g_platform_id;
75 extern DWORD g_MinorVersion;
77 // from MicroSoft SDK (KES) is the diff between Jan 1 1601 and Jan 1 1970
79 #define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000ULL
81 #define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000I64
84 #define WIN32_FILETIME_SCALE 10000000 // 100ns/second
86 void conv_unix_to_win32_path(const char *name, char *win32_name, DWORD dwSize)
88 const char *fname = name;
89 char *tname = win32_name;
91 Dmsg0(100, "Enter convert_unix_to_win32_path\n");
93 if ((name[0] == '/' || name[0] == '\\') &&
94 (name[1] == '/' || name[1] == '\\') &&
96 (name[3] == '/' || name[3] == '\\')) {
101 *win32_name++ = '\\';
104 } else if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS &&
105 g_pVSSPathConvert == NULL) {
106 /* allow path to be 32767 bytes */
107 *win32_name++ = '\\';
108 *win32_name++ = '\\';
110 *win32_name++ = '\\';
114 /* Check for Unix separator and convert to Win32 */
115 if (name[0] == '/' && name[1] == '/') { /* double slash? */
116 name++; /* yes, skip first one */
119 *win32_name++ = '\\'; /* convert char */
120 /* If Win32 separated that is "quoted", remove quote */
121 } else if (*name == '\\' && name[1] == '\\') {
122 *win32_name++ = '\\';
123 name++; /* skip first \ */
125 *win32_name++ = *name; /* copy character */
129 /* Strip any trailing slash, if we stored something */
130 /* but leave "c:\" with backslash (root directory case */
131 if (*fname != 0 && win32_name[-1] == '\\' && strlen (fname) != 3) {
137 /* here we convert to VSS specific file name which
138 can get longer because VSS will make something like
139 \\\\?\\GLOBALROOT\\Device\\HarddiskVolumeShadowCopy1\\bacula\\uninstall.exe
140 from c:\bacula\uninstall.exe
142 Dmsg1(100, "path=%s\n", tname);
143 if (g_pVSSPathConvert != NULL) {
144 POOLMEM *pszBuf = get_pool_memory (PM_FNAME);
145 pszBuf = check_pool_memory_size(pszBuf, dwSize);
146 bstrncpy(pszBuf, tname, strlen(tname)+1);
147 g_pVSSPathConvert(pszBuf, tname, dwSize);
148 free_pool_memory(pszBuf);
151 Dmsg1(100, "Leave cvt_u_to_win32_path path=%s\n", tname);
154 /* Conversion of a Unix filename to a Win32 filename */
155 void unix_name_to_win32(POOLMEM **win32_name, char *name)
157 /* One extra byte should suffice, but we double it */
158 /* add MAX_PATH bytes for VSS shadow copy name */
159 DWORD dwSize = 2*strlen(name)+MAX_PATH;
160 *win32_name = check_pool_memory_size(*win32_name, dwSize);
161 conv_unix_to_win32_path(name, *win32_name, dwSize);
165 make_wchar_win32_path(POOLMEM *pszUCSPath, BOOL *pBIsRawPath /*= NULL*/)
167 /* created 02/27/2006 Thorsten Engel
169 * This function expects an UCS-encoded standard wchar_t in pszUCSPath and
170 * will complete the input path to an absolue path of the form \\?\c:\path\file
172 * With this trick, it is possible to have 32K characters long paths.
174 * Optionally one can use pBIsRawPath to determine id pszUCSPath contains a path
175 * to a raw windows partition.
178 Dmsg0(100, "Enter wchar_win32_path\n");
180 *pBIsRawPath = FALSE; /* Initialize, set later */
183 if (!p_GetCurrentDirectoryW) {
184 Dmsg0(100, "Leave wchar_win32_path no change \n");
188 wchar_t *name = (wchar_t *)pszUCSPath;
190 /* if it has already the desired form, exit without changes */
191 if (wcslen(name) > 3 && wcsncmp(name, L"\\\\?\\", 4) == 0) {
192 Dmsg0(100, "Leave wchar_win32_path no change \n");
196 POOLMEM *pwszBuf = get_pool_memory(PM_FNAME);
197 POOLMEM *pwszCurDirBuf = get_pool_memory(PM_FNAME);
198 DWORD dwCurDirPathSize = 0;
200 /* get buffer with enough size (name+max 6. wchars+1 null terminator */
201 DWORD dwBufCharsNeeded = (wcslen(name)+7);
202 pwszBuf = check_pool_memory_size(pwszBuf, dwBufCharsNeeded*sizeof(wchar_t));
204 /* add \\?\ to support 32K long filepaths
205 it is important to make absolute paths, so we add drive and
206 current path if necessary */
208 BOOL bAddDrive = TRUE;
209 BOOL bAddCurrentPath = TRUE;
210 BOOL bAddPrefix = TRUE;
212 /* does path begin with drive? if yes, it is absolute */
213 if (wcslen(name) >= 3 && (iswalpha (*name) && *(name+1) == ':'
214 && (*(name+2) == '\\' || *(name+2) == '/'))) {
216 bAddCurrentPath = FALSE;
219 /* is path absolute? */
220 if (*name == '/' || *name == '\\')
221 bAddCurrentPath = FALSE;
223 /* is path relative to itself?, if yes, skip ./ */
224 if (wcslen(name) > 2 && ((wcsncmp(name, L"./", 2) == 0) || (wcsncmp(name, L".\\", 2) == 0))) {
228 /* is path of form '//./'? */
229 if (wcslen(name) > 3 && ((wcsncmp(name, L"//./", 4) == 0) || (wcsncmp(name, L"\\\\.\\", 4) == 0))) {
231 bAddCurrentPath = FALSE;
238 int nParseOffset = 0;
240 /* add 4 bytes header */
243 wcscpy((wchar_t *)pwszBuf, L"\\\\?\\");
246 /* get current path if needed */
247 if (bAddDrive || bAddCurrentPath) {
248 dwCurDirPathSize = p_GetCurrentDirectoryW(0, NULL);
249 if (dwCurDirPathSize > 0) {
250 /* get directory into own buffer as it may either return c:\... or \\?\C:\.... */
251 pwszCurDirBuf = check_pool_memory_size(pwszCurDirBuf, (dwCurDirPathSize+1)*sizeof(wchar_t));
252 p_GetCurrentDirectoryW(dwCurDirPathSize,(wchar_t *)pwszCurDirBuf);
254 /* we have no info for doing so */
256 bAddCurrentPath = FALSE;
261 /* add drive if needed */
262 if (bAddDrive && !bAddCurrentPath) {
265 if (dwCurDirPathSize > 3 && wcsncmp((LPCWSTR)pwszCurDirBuf, L"\\\\?\\", 4) == 0) {
266 /* copy drive character */
267 wcsncpy((wchar_t *)szDrive, (LPCWSTR)pwszCurDirBuf+4, 2);
269 /* copy drive character */
270 wcsncpy((wchar_t *)szDrive, (LPCWSTR)pwszCurDirBuf, 2);
275 wcscat((wchar_t *)pwszBuf, szDrive);
279 /* add path if needed */
280 if (bAddCurrentPath) {
281 /* the 1 add. character is for the eventually added backslash */
282 dwBufCharsNeeded += dwCurDirPathSize+1;
283 pwszBuf = check_pool_memory_size(pwszBuf, dwBufCharsNeeded*sizeof(wchar_t));
284 /* get directory into own buffer as it may either return c:\... or \\?\C:\.... */
286 if (dwCurDirPathSize > 3 && wcsncmp((LPCWSTR)pwszCurDirBuf, L"\\\\?\\", 4) == 0) {
287 /* copy complete string */
288 wcscpy((wchar_t *)pwszBuf, (LPCWSTR)pwszCurDirBuf);
291 wcscat((wchar_t *)pwszBuf, (LPCWSTR)pwszCurDirBuf);
294 nParseOffset = wcslen((LPCWSTR) pwszBuf);
296 /* check if path ends with backslash, if not, add one */
297 if (*((wchar_t *)pwszBuf+nParseOffset-1) != L'\\') {
298 wcscat((wchar_t *)pwszBuf, L"\\");
304 wchar_t *win32_name = (wchar_t *)pwszBuf+nParseOffset;
307 /* Check for Unix separator and convert to Win32 */
309 *win32_name++ = '\\'; /* convert char */
310 /* If Win32 separated that is "quoted", remove quote */
311 /* HELPME (Thorsten Engel): I don't understand the following part
312 * and it removes a backslash from e.g. "\\.\c:" which I need for
313 * RAW device access. So I took it out.
316 } else if (*name == '\\' && name[1] == '\\') {
317 *win32_name++ = '\\';
318 name++; /* skip first \ */
321 *win32_name++ = *name; /* copy character */
326 /* null terminate string */
329 /* here we convert to VSS specific file name which
330 * can get longer because VSS will make something like
331 * \\\\?\\GLOBALROOT\\Device\\HarddiskVolumeShadowCopy1\\bacula\\uninstall.exe
332 * from c:\bacula\uninstall.exe
334 if (g_pVSSPathConvertW != NULL) {
335 /* is output buffer large enough? */
336 pwszBuf = check_pool_memory_size(pwszBuf, (dwBufCharsNeeded+MAX_PATH)*sizeof(wchar_t));
337 /* create temp. buffer */
338 POOLMEM* pszBuf = get_pool_memory(PM_FNAME);
339 pszBuf = check_pool_memory_size(pszBuf, (dwBufCharsNeeded+MAX_PATH)*sizeof(wchar_t));
344 wcsncpy((wchar_t *)pszBuf, (wchar_t *)pwszBuf+nParseOffset, wcslen((wchar_t *)pwszBuf)+1-nParseOffset);
345 g_pVSSPathConvertW((wchar_t *)pszBuf, (wchar_t *)pwszBuf, dwBufCharsNeeded+MAX_PATH);
346 free_pool_memory(pszBuf);
349 free_pool_memory(pszUCSPath);
350 free_pool_memory(pwszCurDirBuf);
352 Dmsg1(100, "Leave wchar_win32_path=%s\n", pwszBuf);
357 wchar_2_UTF8(char *pszUTF, const wchar_t *pszUCS, int cchChar)
359 /* the return value is the number of bytes written to the buffer.
360 The number includes the byte for the null terminator. */
362 if (p_WideCharToMultiByte) {
363 int nRet = p_WideCharToMultiByte(CP_UTF8,0,pszUCS,-1,pszUTF,cchChar,NULL,NULL);
372 UTF8_2_wchar(POOLMEM **ppszUCS, const char *pszUTF)
374 /* the return value is the number of wide characters written to the buffer. */
375 /* convert null terminated string from utf-8 to ucs2, enlarge buffer if necessary */
377 if (p_MultiByteToWideChar) {
378 /* strlen of UTF8 +1 is enough */
379 DWORD cchSize = (strlen(pszUTF)+1);
380 *ppszUCS = check_pool_memory_size(*ppszUCS, cchSize*sizeof (wchar_t));
382 int nRet = p_MultiByteToWideChar(CP_UTF8, 0, pszUTF, -1, (LPWSTR) *ppszUCS,cchSize);
392 wchar_win32_path(const char *name, wchar_t *win32_name)
394 const char *fname = name;
396 /* Check for Unix separator and convert to Win32 */
398 *win32_name++ = '\\'; /* convert char */
399 /* If Win32 separated that is "quoted", remove quote */
400 } else if (*name == '\\' && name[1] == '\\') {
401 *win32_name++ = '\\';
402 name++; /* skip first \ */
404 *win32_name++ = *name; /* copy character */
408 /* Strip any trailing slash, if we stored something */
409 if (*fname != 0 && win32_name[-1] == '\\') {
417 make_win32_path_UTF8_2_wchar(POOLMEM **pszUCS, const char *pszUTF, BOOL* pBIsRawPath /*= NULL*/)
420 /* if we find the utf8 string in cache, we use the cached ucs2 version.
421 we compare the stringlength first (quick check) and then compare the content.
423 if (g_dwWin32ConvUTF8strlen == strlen(pszUTF)) {
424 if (bstrcmp(pszUTF, g_pWin32ConvUTF8Cache)) {
425 int32_t nBufSize = sizeof_pool_memory(g_pWin32ConvUCS2Cache);
426 *pszUCS = check_pool_memory_size(*pszUCS, nBufSize);
427 wcscpy((LPWSTR) *pszUCS, (LPWSTR) g_pWin32ConvUCS2Cache);
429 return nBufSize / sizeof (WCHAR);
433 /* helper to convert from utf-8 to UCS-2 and to complete a path for 32K path syntax */
434 int nRet = UTF8_2_wchar(pszUCS, pszUTF);
436 #ifdef USE_WIN32_32KPATHCONVERSION
437 /* add \\?\ to support 32K long filepaths */
438 *pszUCS = make_wchar_win32_path(*pszUCS, pBIsRawPath);
441 *pBIsRawPath = FALSE;
445 g_pWin32ConvUCS2Cache = check_pool_memory_size(g_pWin32ConvUCS2Cache, sizeof_pool_memory(*pszUCS));
446 wcscpy((LPWSTR) g_pWin32ConvUCS2Cache, (LPWSTR) *pszUCS);
448 g_dwWin32ConvUTF8strlen = strlen(pszUTF);
449 g_pWin32ConvUTF8Cache = check_pool_memory_size(g_pWin32ConvUTF8Cache, g_dwWin32ConvUTF8strlen+1);
450 bstrncpy(g_pWin32ConvUTF8Cache, pszUTF, g_dwWin32ConvUTF8strlen+1);
456 #if !defined(_MSC_VER) || (_MSC_VER < 1400) // VC8+
463 int fcntl(int fd, int cmd)
468 int chmod(const char *, mode_t)
473 int chown(const char *k, uid_t, gid_t)
478 int lchown(const char *k, uid_t, gid_t)
490 srandom(unsigned int seed)
494 // /////////////////////////////////////////////////////////////////
495 // convert from Windows concept of time to Unix concept of time
496 // /////////////////////////////////////////////////////////////////
498 cvt_utime_to_ftime(const time_t &time, FILETIME &wintime)
500 uint64_t mstime = time;
501 mstime *= WIN32_FILETIME_SCALE;
502 mstime += WIN32_FILETIME_ADJUST;
504 #if defined(_MSC_VER)
505 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffI64);
507 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffUL);
509 wintime.dwHighDateTime = (DWORD) ((mstime>>32)& 0xffffffffUL);
513 cvt_ftime_to_utime(const FILETIME &time)
515 uint64_t mstime = time.dwHighDateTime;
517 mstime |= time.dwLowDateTime;
519 mstime -= WIN32_FILETIME_ADJUST;
520 mstime /= WIN32_FILETIME_SCALE; // convert to seconds.
522 return (time_t) (mstime & 0xffffffff);
530 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
531 FORMAT_MESSAGE_FROM_SYSTEM |
532 FORMAT_MESSAGE_IGNORE_INSERTS,
535 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default lang
540 /* Strip any \r or \n */
541 char *rval = (char *) lpMsgBuf;
542 char *cp = strchr(rval, '\r');
546 cp = strchr(rval, '\n');
555 statDir(const char *file, struct stat *sb)
557 WIN32_FIND_DATAW info_w; // window's file info
558 WIN32_FIND_DATAA info_a; // window's file info
560 // cache some common vars to make code more transparent
561 DWORD* pdwFileAttributes;
562 DWORD* pnFileSizeHigh;
563 DWORD* pnFileSizeLow;
564 FILETIME* pftLastAccessTime;
565 FILETIME* pftLastWriteTime;
566 FILETIME* pftCreationTime;
568 if (file[1] == ':' && file[2] == 0) {
569 Dmsg1(99, "faking ROOT attrs(%s).\n", file);
570 sb->st_mode = S_IFDIR;
571 sb->st_mode |= S_IREAD|S_IEXEC|S_IWRITE;
578 HANDLE h = INVALID_HANDLE_VALUE;
580 // use unicode or ascii
581 if (p_FindFirstFileW) {
582 POOLMEM* pwszBuf = get_pool_memory (PM_FNAME);
583 make_win32_path_UTF8_2_wchar(&pwszBuf, file);
585 h = p_FindFirstFileW((LPCWSTR) pwszBuf, &info_w);
586 free_pool_memory(pwszBuf);
588 pdwFileAttributes = &info_w.dwFileAttributes;
589 pnFileSizeHigh = &info_w.nFileSizeHigh;
590 pnFileSizeLow = &info_w.nFileSizeLow;
591 pftLastAccessTime = &info_w.ftLastAccessTime;
592 pftLastWriteTime = &info_w.ftLastWriteTime;
593 pftCreationTime = &info_w.ftCreationTime;
595 else if (p_FindFirstFileA) {
596 h = p_FindFirstFileA(file, &info_a);
598 pdwFileAttributes = &info_a.dwFileAttributes;
599 pnFileSizeHigh = &info_a.nFileSizeHigh;
600 pnFileSizeLow = &info_a.nFileSizeLow;
601 pftLastAccessTime = &info_a.ftLastAccessTime;
602 pftLastWriteTime = &info_a.ftLastWriteTime;
603 pftCreationTime = &info_a.ftCreationTime;
606 if (h == INVALID_HANDLE_VALUE) {
607 const char *err = errorString();
608 Dmsg2(99, "FindFirstFile(%s):%s\n", file, err);
609 LocalFree((void *)err);
610 errno = b_errno_win32;
614 sb->st_mode = 0777; /* start with everything */
615 if (*pdwFileAttributes & FILE_ATTRIBUTE_READONLY)
616 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
617 if (*pdwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
618 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
619 if (*pdwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
620 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
621 sb->st_mode |= S_IFDIR;
623 sb->st_size = *pnFileSizeHigh;
625 sb->st_size |= *pnFileSizeLow;
626 sb->st_blksize = 4096;
627 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
629 sb->st_atime = cvt_ftime_to_utime(*pftLastAccessTime);
630 sb->st_mtime = cvt_ftime_to_utime(*pftLastWriteTime);
631 sb->st_ctime = cvt_ftime_to_utime(*pftCreationTime);
638 fstat(int fd, struct stat *sb)
640 BY_HANDLE_FILE_INFORMATION info;
643 if (!GetFileInformationByHandle((HANDLE)fd, &info)) {
644 const char *err = errorString();
645 Dmsg2(99, "GetfileInformationByHandle(%s): %s\n", tmpbuf, err);
646 LocalFree((void *)err);
647 errno = b_errno_win32;
651 sb->st_dev = info.dwVolumeSerialNumber;
652 sb->st_ino = info.nFileIndexHigh;
654 sb->st_ino |= info.nFileIndexLow;
655 sb->st_nlink = (short)info.nNumberOfLinks;
656 if (sb->st_nlink > 1) {
657 Dmsg1(99, "st_nlink=%d\n", sb->st_nlink);
660 sb->st_mode = 0777; /* start with everything */
661 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
662 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
663 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
664 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
665 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
666 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
667 sb->st_mode |= S_IFREG;
669 sb->st_size = info.nFileSizeHigh;
671 sb->st_size |= info.nFileSizeLow;
672 sb->st_blksize = 4096;
673 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
674 sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
675 sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
676 sb->st_ctime = cvt_ftime_to_utime(info.ftCreationTime);
682 stat2(const char *file, struct stat *sb)
687 conv_unix_to_win32_path(file, tmpbuf, 1024);
689 DWORD attr = (DWORD)-1;
691 if (p_GetFileAttributesW) {
692 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
693 make_win32_path_UTF8_2_wchar(&pwszBuf, tmpbuf);
695 attr = p_GetFileAttributesW((LPCWSTR) pwszBuf);
696 free_pool_memory(pwszBuf);
697 } else if (p_GetFileAttributesA) {
698 attr = p_GetFileAttributesA(tmpbuf);
701 if (attr == (DWORD)-1) {
702 const char *err = errorString();
703 Dmsg2(99, "GetFileAttributes(%s): %s\n", tmpbuf, err);
704 LocalFree((void *)err);
705 errno = b_errno_win32;
709 if (attr & FILE_ATTRIBUTE_DIRECTORY)
710 return statDir(tmpbuf, sb);
712 h = CreateFileA(tmpbuf, GENERIC_READ,
713 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
715 if (h == INVALID_HANDLE_VALUE) {
716 const char *err = errorString();
717 Dmsg2(99, "Cannot open file for stat (%s):%s\n", tmpbuf, err);
718 LocalFree((void *)err);
719 errno = b_errno_win32;
723 rval = fstat((int)h, sb);
730 stat(const char *file, struct stat *sb)
732 WIN32_FILE_ATTRIBUTE_DATA data;
736 memset(sb, 0, sizeof(*sb));
738 /* why not allow win 95 to use p_GetFileAttributesExA ?
739 * this function allows _some_ open files to be stat'ed
740 * if (g_platform_id == VER_PLATFORM_WIN32_WINDOWS) {
741 * return stat2(file, sb);
745 if (p_GetFileAttributesExW) {
746 /* dynamically allocate enough space for UCS2 filename */
747 POOLMEM* pwszBuf = get_pool_memory (PM_FNAME);
748 make_win32_path_UTF8_2_wchar(&pwszBuf, file);
750 BOOL b = p_GetFileAttributesExW((LPCWSTR) pwszBuf, GetFileExInfoStandard, &data);
751 free_pool_memory(pwszBuf);
754 return stat2(file, sb);
756 } else if (p_GetFileAttributesExA) {
757 if (!p_GetFileAttributesExA(file, GetFileExInfoStandard, &data)) {
758 return stat2(file, sb);
761 return stat2(file, sb);
764 sb->st_mode = 0777; /* start with everything */
765 if (data.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
766 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
768 if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
769 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
771 if (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
772 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
774 if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
775 sb->st_mode |= S_IFDIR;
777 sb->st_mode |= S_IFREG;
781 sb->st_size = data.nFileSizeHigh;
783 sb->st_size |= data.nFileSizeLow;
784 sb->st_blksize = 4096;
785 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
786 sb->st_atime = cvt_ftime_to_utime(data.ftLastAccessTime);
787 sb->st_mtime = cvt_ftime_to_utime(data.ftLastWriteTime);
788 sb->st_ctime = cvt_ftime_to_utime(data.ftCreationTime);
792 int fcntl(int fd, int cmd, long arg)
815 lstat(const char *file, struct stat *sb)
817 return stat(file, sb);
833 execvp(const char *, char *[]) {
854 waitpid(int, int*, int)
861 readlink(const char *, char *, int)
870 strcasecmp(const char *s1, const char *s2)
872 register int ch1, ch2;
875 return 0; /* strings are equal if same object. */
885 } while (ch1 != 0 && tolower(ch1) == tolower(ch2));
892 strncasecmp(const char *s1, const char *s2, int len)
894 register int ch1 = 0, ch2 = 0;
897 return 0; /* strings are equal if same object. */
908 if (ch1 == 0 || tolower(ch1) != tolower(ch2)) break;
915 gettimeofday(struct timeval *tv, struct timezone *)
925 if (!SystemTimeToFileTime(&now, &tmp)) {
926 errno = b_errno_win32;
930 int64_t _100nsec = tmp.dwHighDateTime;
932 _100nsec |= tmp.dwLowDateTime;
933 _100nsec -= WIN32_FILETIME_ADJUST;
935 tv->tv_sec =(long) (_100nsec / 10000000);
936 tv->tv_usec = (long) ((_100nsec % 10000000)/10);
941 /* For apcupsd this is in src/lib/wincompat.c */
942 extern "C" void syslog(int type, const char *fmt, ...)
944 /*#ifndef HAVE_CONSOLE
945 MessageBox(NULL, msg, "Bacula", MB_OK);
966 // implement opendir/readdir/closedir on top of window's API
970 WIN32_FIND_DATAA data_a; // window's file info (ansii version)
971 WIN32_FIND_DATAW data_w; // window's file info (wchar version)
972 const char *spec; // the directory we're traversing
973 HANDLE dirh; // the search handle
974 BOOL valid_a; // the info in data_a field is valid
975 BOOL valid_w; // the info in data_w field is valid
976 UINT32 offset; // pseudo offset for d_off
980 opendir(const char *path)
982 /* enough space for VSS !*/
983 int max_len = strlen(path) + MAX_PATH;
990 Dmsg1(100, "Opendir path=%s\n", path);
991 rval = (_dir *)malloc(sizeof(_dir));
992 memset (rval, 0, sizeof (_dir));
993 if (rval == NULL) return NULL;
994 char *tspec = (char *)malloc(max_len);
995 if (tspec == NULL) return NULL;
997 conv_unix_to_win32_path(path, tspec, max_len);
998 Dmsg1(100, "win32 path=%s\n", tspec);
1000 // add backslash only if there is none yet (think of c:\)
1001 if (tspec[strlen(tspec)-1] != '\\')
1002 bstrncat(tspec, "\\*", max_len);
1004 bstrncat(tspec, "*", max_len);
1008 // convert to wchar_t
1009 if (p_FindFirstFileW) {
1010 POOLMEM* pwcBuf = get_pool_memory(PM_FNAME);;
1011 make_win32_path_UTF8_2_wchar(&pwcBuf, rval->spec);
1013 rval->dirh = p_FindFirstFileW((LPCWSTR)pwcBuf, &rval->data_w);
1015 free_pool_memory(pwcBuf);
1017 if (rval->dirh != INVALID_HANDLE_VALUE)
1019 } else if (p_FindFirstFileA) {
1020 rval->dirh = p_FindFirstFileA(rval->spec, &rval->data_a);
1022 if (rval->dirh != INVALID_HANDLE_VALUE)
1027 Dmsg3(99, "opendir(%s)\n\tspec=%s,\n\tFindFirstFile returns %d\n",
1028 path, rval->spec, rval->dirh);
1031 if (rval->dirh == INVALID_HANDLE_VALUE)
1034 if (rval->valid_w) {
1035 Dmsg1(99, "\tFirstFile=%s\n", rval->data_w.cFileName);
1038 if (rval->valid_a) {
1039 Dmsg1(99, "\tFirstFile=%s\n", rval->data_a.cFileName);
1045 free((void *)rval->spec);
1047 errno = b_errno_win32;
1054 _dir *dp = (_dir *)dirp;
1055 FindClose(dp->dirh);
1056 free((void *)dp->spec);
1062 typedef struct _WIN32_FIND_DATA {
1063 DWORD dwFileAttributes;
1064 FILETIME ftCreationTime;
1065 FILETIME ftLastAccessTime;
1066 FILETIME ftLastWriteTime;
1067 DWORD nFileSizeHigh;
1071 TCHAR cFileName[MAX_PATH];
1072 TCHAR cAlternateFileName[14];
1073 } WIN32_FIND_DATA, *PWIN32_FIND_DATA;
1077 copyin(struct dirent &dp, const char *fname)
1081 char *cp = dp.d_name;
1091 readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
1093 _dir *dp = (_dir *)dirp;
1094 if (dp->valid_w || dp->valid_a) {
1095 entry->d_off = dp->offset;
1099 char szBuf[MAX_PATH_UTF8+1];
1100 wchar_2_UTF8(szBuf,dp->data_w.cFileName);
1101 dp->offset += copyin(*entry, szBuf);
1102 } else if (dp->valid_a) { // copy ansi (only 1 will be valid)
1103 dp->offset += copyin(*entry, dp->data_a.cFileName);
1106 *result = entry; /* return entry address */
1107 Dmsg4(99, "readdir_r(%p, { d_name=\"%s\", d_reclen=%d, d_off=%d\n",
1108 dirp, entry->d_name, entry->d_reclen, entry->d_off);
1110 // Dmsg0(99, "readdir_r !valid\n");
1111 errno = b_errno_win32;
1115 // get next file, try unicode first
1116 if (p_FindNextFileW)
1117 dp->valid_w = p_FindNextFileW(dp->dirh, &dp->data_w);
1118 else if (p_FindNextFileA)
1119 dp->valid_a = p_FindNextFileA(dp->dirh, &dp->data_a);
1121 dp->valid_a = FALSE;
1122 dp->valid_w = FALSE;
1129 * Dotted IP address to network address
1135 inet_aton(const char *a, struct in_addr *inp)
1138 uint32_t acc = 0, tmp = 0;
1141 if (!isdigit(*cp)) { /* first char must be digit */
1142 return 0; /* error */
1146 tmp = (tmp * 10) + (*cp -'0');
1147 } else if (*cp == '.' || *cp == 0) {
1149 return 0; /* error */
1151 acc = (acc << 8) + tmp;
1155 return 0; /* error */
1157 } while (*cp++ != 0);
1158 if (dotc != 4) { /* want 3 .'s plus EOS */
1159 return 0; /* error */
1161 inp->s_addr = htonl(acc); /* store addr in network format */
1166 nanosleep(const struct timespec *req, struct timespec *rem)
1169 rem->tv_sec = rem->tv_nsec = 0;
1170 Sleep((req->tv_sec * 1000) + (req->tv_nsec/100000));
1175 init_signals(void terminate(int sig))
1181 init_stack_dump(void)
1188 pathconf(const char *path, int name)
1192 if (strncmp(path, "\\\\?\\", 4) == 0)
1204 WORD wVersionRequested = MAKEWORD( 1, 1);
1207 int err = WSAStartup(wVersionRequested, &wsaData);
1211 printf("Can not start Windows Sockets\n");
1221 win32_chdir(const char *dir)
1223 if (p_SetCurrentDirectoryW) {
1224 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1225 make_win32_path_UTF8_2_wchar(&pwszBuf, dir);
1227 BOOL b=p_SetCurrentDirectoryW((LPCWSTR)pwszBuf);
1229 free_pool_memory(pwszBuf);
1232 errno = b_errno_win32;
1236 else if (p_SetCurrentDirectoryA) {
1237 if (0 == p_SetCurrentDirectoryA(dir)) {
1238 errno = b_errno_win32;
1248 win32_mkdir(const char *dir)
1251 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1252 make_win32_path_UTF8_2_wchar(&pwszBuf, dir);
1254 int n = p_wmkdir((LPCWSTR)pwszBuf);
1255 free_pool_memory(pwszBuf);
1264 win32_getcwd(char *buf, int maxlen)
1268 if (p_GetCurrentDirectoryW) {
1269 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1270 pwszBuf = check_pool_memory_size (pwszBuf, maxlen*sizeof(wchar_t));
1272 n = p_GetCurrentDirectoryW(maxlen, (LPWSTR) pwszBuf);
1274 n = wchar_2_UTF8 (buf, (wchar_t *)pwszBuf, maxlen)-1;
1275 free_pool_memory(pwszBuf);
1277 } else if (p_GetCurrentDirectoryA)
1278 n = p_GetCurrentDirectoryA(maxlen, buf);
1280 if (n == 0 || n > maxlen) return NULL;
1282 if (n+1 > maxlen) return NULL;
1291 win32_fputs(const char *string, FILE *stream)
1293 /* we use WriteConsoleA / WriteConsoleA
1294 so we can be sure that unicode support works on win32.
1295 with fallback if something fails
1298 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
1299 if (hOut && (hOut != INVALID_HANDLE_VALUE) && p_WideCharToMultiByte &&
1300 p_MultiByteToWideChar && (stream == stdout)) {
1302 POOLMEM* pwszBuf = get_pool_memory(PM_MESSAGE);
1304 DWORD dwCharsWritten;
1307 dwChars = UTF8_2_wchar(&pwszBuf, string);
1309 /* try WriteConsoleW */
1310 if (WriteConsoleW (hOut, pwszBuf, dwChars-1, &dwCharsWritten, NULL)) {
1311 free_pool_memory(pwszBuf);
1312 return dwCharsWritten;
1315 /* convert to local codepage and try WriteConsoleA */
1316 POOLMEM* pszBuf = get_pool_memory(PM_MESSAGE);
1317 pszBuf = check_pool_memory_size(pszBuf, dwChars+1);
1319 dwChars = p_WideCharToMultiByte(GetConsoleOutputCP(),0,(LPCWSTR) pwszBuf,-1,pszBuf,dwChars,NULL,NULL);
1320 free_pool_memory(pwszBuf);
1322 if (WriteConsoleA (hOut, pszBuf, dwChars-1, &dwCharsWritten, NULL)) {
1323 free_pool_memory(pszBuf);
1324 return dwCharsWritten;
1328 return fputs(string, stream);
1332 win32_cgets (char* buffer, int len)
1334 /* we use console ReadConsoleA / ReadConsoleW to be able to read unicode
1335 from the win32 console and fallback if seomething fails */
1337 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
1338 if (hIn && (hIn != INVALID_HANDLE_VALUE) && p_WideCharToMultiByte && p_MultiByteToWideChar) {
1340 wchar_t wszBuf[1024];
1343 /* nt and unicode conversion */
1344 if (ReadConsoleW (hIn, wszBuf, 1024, &dwRead, NULL)) {
1346 /* null terminate at end */
1347 if (wszBuf[dwRead-1] == L'\n') {
1348 wszBuf[dwRead-1] = L'\0';
1352 if (wszBuf[dwRead-1] == L'\r') {
1353 wszBuf[dwRead-1] = L'\0';
1357 wchar_2_UTF8(buffer, wszBuf, len);
1361 /* win 9x and unicode conversion */
1362 if (ReadConsoleA (hIn, szBuf, 1024, &dwRead, NULL)) {
1364 /* null terminate at end */
1365 if (szBuf[dwRead-1] == L'\n') {
1366 szBuf[dwRead-1] = L'\0';
1370 if (szBuf[dwRead-1] == L'\r') {
1371 szBuf[dwRead-1] = L'\0';
1375 /* convert from ansii to wchar_t */
1376 p_MultiByteToWideChar(GetConsoleCP(), 0, szBuf, -1, wszBuf,1024);
1377 /* convert from wchar_t to UTF-8 */
1378 if (wchar_2_UTF8(buffer, wszBuf, len))
1384 if (fgets(buffer, len, stdin))
1391 win32_unlink(const char *filename)
1395 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1396 make_win32_path_UTF8_2_wchar(&pwszBuf, filename);
1398 nRetCode = _wunlink((LPCWSTR) pwszBuf);
1400 /* special case if file is readonly,
1401 we retry but unset attribute before */
1402 if (nRetCode == -1 && errno == EACCES && p_SetFileAttributesW && p_GetFileAttributesW) {
1403 DWORD dwAttr = p_GetFileAttributesW((LPCWSTR)pwszBuf);
1404 if (dwAttr != INVALID_FILE_ATTRIBUTES) {
1405 if (p_SetFileAttributesW((LPCWSTR)pwszBuf, dwAttr & ~FILE_ATTRIBUTE_READONLY)) {
1406 nRetCode = _wunlink((LPCWSTR) pwszBuf);
1407 /* reset to original if it didn't help */
1409 p_SetFileAttributesW((LPCWSTR)pwszBuf, dwAttr);
1413 free_pool_memory(pwszBuf);
1415 nRetCode = _unlink(filename);
1417 /* special case if file is readonly,
1418 we retry but unset attribute before */
1419 if (nRetCode == -1 && errno == EACCES && p_SetFileAttributesA && p_GetFileAttributesA) {
1420 DWORD dwAttr = p_GetFileAttributesA(filename);
1421 if (dwAttr != INVALID_FILE_ATTRIBUTES) {
1422 if (p_SetFileAttributesA(filename, dwAttr & ~FILE_ATTRIBUTE_READONLY)) {
1423 nRetCode = _unlink(filename);
1424 /* reset to original if it didn't help */
1426 p_SetFileAttributesA(filename, dwAttr);
1435 #include "mswinver.h"
1437 char WIN_VERSION_LONG[64];
1438 char WIN_VERSION[32];
1439 char WIN_RAWVERSION[32];
1446 static winver INIT; // cause constructor to be called before main()
1449 winver::winver(void)
1451 const char *version = "";
1452 const char *platform = "";
1453 OSVERSIONINFO osvinfo;
1454 osvinfo.dwOSVersionInfoSize = sizeof(osvinfo);
1456 // Get the current OS version
1457 if (!GetVersionEx(&osvinfo)) {
1458 version = "Unknown";
1459 platform = "Unknown";
1461 const int ver = _mkversion(osvinfo.dwPlatformId,
1462 osvinfo.dwMajorVersion,
1463 osvinfo.dwMinorVersion);
1464 snprintf(WIN_RAWVERSION, sizeof(WIN_RAWVERSION), "Windows %#08x", ver);
1467 case MS_WINDOWS_95: (version = "Windows 95"); break;
1468 case MS_WINDOWS_98: (version = "Windows 98"); break;
1469 case MS_WINDOWS_ME: (version = "Windows ME"); break;
1470 case MS_WINDOWS_NT4:(version = "Windows NT 4.0"); platform = "NT"; break;
1471 case MS_WINDOWS_2K: (version = "Windows 2000");platform = "NT"; break;
1472 case MS_WINDOWS_XP: (version = "Windows XP");platform = "NT"; break;
1473 case MS_WINDOWS_S2003: (version = "Windows Server 2003");platform = "NT"; break;
1474 default: version = WIN_RAWVERSION; break;
1477 bstrncpy(WIN_VERSION_LONG, version, sizeof(WIN_VERSION_LONG));
1478 snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %lu.%lu.%lu",
1479 platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
1482 HANDLE h = CreateFile("G:\\foobar", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
1486 BPIPE *b = open_bpipe("ls -l", 10, "r");
1488 while (!feof(b->rfd)) {
1489 fgets(buf, sizeof(buf), b->rfd);
1495 BOOL CreateChildProcess(VOID);
1496 VOID WriteToPipe(VOID);
1497 VOID ReadFromPipe(VOID);
1498 VOID ErrorExit(LPCSTR);
1499 VOID ErrMsg(LPTSTR, BOOL);
1502 * Check for a quoted path, if an absolute path name is given and it contains
1503 * spaces it will need to be quoted. i.e. "c:/Program Files/foo/bar.exe"
1504 * CreateProcess() says the best way to ensure proper results with executables
1505 * with spaces in path or filename is to quote the string.
1508 getArgv0(const char *cmdline)
1513 for (cp = cmdline; *cp; cp++)
1518 if (!inquote && isspace(*cp))
1523 int len = cp - cmdline;
1524 char *rval = (char *)malloc(len+1);
1537 * Extracts the executable or script name from the first string in
1540 * If the name contains blanks then it must be quoted with double quotes,
1541 * otherwise quotes are optional. If the name contains blanks then it
1542 * will be converted to a short name.
1544 * The optional quotes will be removed. The result is copied to a malloc'ed
1545 * buffer and returned through the pexe argument. The pargs parameter is set
1546 * to the address of the character in cmdline located after the name.
1548 * The malloc'ed buffer returned in *pexe must be freed by the caller.
1551 GetApplicationName(const char *cmdline, char **pexe, const char **pargs)
1553 const char *pExeStart = NULL; /* Start of executable name in cmdline */
1554 const char *pExeEnd = NULL; /* Character after executable name (separator) */
1556 const char *pBasename = NULL; /* Character after last path separator */
1557 const char *pExtension = NULL; /* Period at start of extension */
1559 const char *current = cmdline;
1561 bool bHasBlanks = false;
1562 bool bQuoted = false;
1564 /* Skip initial whitespace */
1566 while (*current == ' ' || *current == '\t')
1571 /* Calculate start of name and determine if quoted */
1573 if (*current == '"') {
1574 pExeStart = ++current;
1577 pExeStart = current;
1584 * Scan command line looking for path separators (/ and \\) and the
1585 * terminator, either a quote or a blank. The location of the
1586 * extension is also noted.
1589 for ( ; *current != '\0'; current++)
1591 if (*current == ' ') {
1593 } else if (*current == '.') {
1594 pExtension = current;
1595 } else if ((*current == '\\' || *current == '/') && current[1] != '\0') {
1596 pBasename = ¤t[1];
1600 /* Check for terminator, either quote or blank */
1602 if (*current != '"') {
1606 if (*current != ' ') {
1612 * Hit terminator, remember end of name (address of terminator) and
1613 * start of arguments
1617 if (bQuoted && *current == '"') {
1618 *pargs = ¤t[1];
1626 if (pBasename == NULL) {
1627 pBasename = pExeStart;
1630 if (pExeEnd == NULL) {
1638 bool bHasPathSeparators = pExeStart != pBasename;
1640 /* We have the pointers to all the useful parts of the name */
1642 /* Default extensions in the order cmd.exe uses to search */
1644 static const char ExtensionList[][5] = { ".com", ".exe", ".bat", ".cmd" };
1645 DWORD dwBasePathLength = pExeEnd - pExeStart;
1648 DWORD dwShortNameLength = 0;
1649 char *pPathname = (char *)alloca(MAX_PATHLENGTH + 1);
1650 char *pShortPathname = (char *)alloca(MAX_PATHLENGTH + 1);
1652 pPathname[MAX_PATHLENGTH] = '\0';
1653 pShortPathname[MAX_PATHLENGTH] = '\0';
1655 memcpy(pPathname, pExeStart, dwBasePathLength);
1656 pPathname[dwBasePathLength] = '\0';
1658 if (pExtension == NULL) {
1659 /* Try appending extensions */
1660 for (int index = 0; index < (int)(sizeof(ExtensionList) / sizeof(ExtensionList[0])); index++) {
1662 if (!bHasPathSeparators) {
1663 /* There are no path separators, search in the standard locations */
1664 dwShortNameLength = SearchPath(NULL, pPathname, ExtensionList[index], MAX_PATHLENGTH, pShortPathname, NULL);
1665 if (dwShortNameLength > 0 && dwShortNameLength <= MAX_PATHLENGTH) {
1666 memcpy(pPathname, pShortPathname, dwShortNameLength);
1667 pPathname[dwShortNameLength] = '\0';
1671 bstrncpy(&pPathname[dwBasePathLength], ExtensionList[index], MAX_PATHLENGTH);
1672 if (GetFileAttributes(pPathname) != INVALID_FILE_ATTRIBUTES) {
1678 if (!bHasPathSeparators) {
1679 /* There are no path separators, search in the standard locations */
1680 dwShortNameLength = SearchPath(NULL, pPathname, NULL, MAX_PATHLENGTH, pShortPathname, NULL);
1681 if (dwShortNameLength == 0 || dwShortNameLength > MAX_PATHLENGTH) {
1685 memcpy(pPathname, pShortPathname, dwShortNameLength);
1686 pPathname[dwShortNameLength] = '\0';
1690 dwShortNameLength = GetShortPathName(pPathname, pShortPathname, MAX_PATHLENGTH);
1692 if (dwShortNameLength > 0 && dwShortNameLength <= MAX_PATHLENGTH) {
1693 *pexe = (char *)malloc(dwShortNameLength + 1);
1694 if (*pexe != NULL) {
1695 memcpy(*pexe, pShortPathname, dwShortNameLength + 1);
1703 /* There are no blanks so we don't need to munge the name */
1704 *pexe = (char *)malloc(dwBasePathLength + 1);
1705 if (*pexe != NULL) {
1706 memcpy(*pexe, pExeStart, dwBasePathLength);
1707 (*pexe)[dwBasePathLength] = '\0';
1717 * OK, so it would seem CreateProcess only handles true executables:
1718 * .com or .exe files. So grab $COMSPEC value and pass command line to it.
1721 CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err)
1723 static const char *comspec = NULL;
1724 PROCESS_INFORMATION piProcInfo;
1725 STARTUPINFOA siStartInfo;
1726 BOOL bFuncRetn = FALSE;
1728 if (comspec == NULL) {
1729 comspec = getenv("COMSPEC");
1731 if (comspec == NULL) // should never happen
1732 return INVALID_HANDLE_VALUE;
1734 // Set up members of the PROCESS_INFORMATION structure.
1735 ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
1737 // Set up members of the STARTUPINFO structure.
1739 ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
1740 siStartInfo.cb = sizeof(STARTUPINFO);
1741 // setup new process to use supplied handles for stdin,stdout,stderr
1742 // if supplied handles are not used the send a copy of our STD_HANDLE
1744 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
1746 if (in != INVALID_HANDLE_VALUE)
1747 siStartInfo.hStdInput = in;
1749 siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1751 if (out != INVALID_HANDLE_VALUE)
1752 siStartInfo.hStdOutput = out;
1754 siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1755 if (err != INVALID_HANDLE_VALUE)
1756 siStartInfo.hStdError = err;
1758 siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1760 // Create the child process.
1763 const char *argStart;
1765 if (!GetApplicationName(cmdline, &exeFile, &argStart)) {
1766 return INVALID_HANDLE_VALUE;
1769 int cmdLen = strlen(comspec) + 4 + strlen(exeFile) + strlen(argStart) + 1;
1771 char *cmdLine = (char *)alloca(cmdLen);
1773 snprintf(cmdLine, cmdLen, "%s /c %s%s", comspec, exeFile, argStart);
1777 Dmsg2(150, "Calling CreateProcess(%s, %s, ...)\n", comspec, cmdLine);
1779 // try to execute program
1780 bFuncRetn = CreateProcessA(comspec,
1781 cmdLine, // command line
1782 NULL, // process security attributes
1783 NULL, // primary thread security attributes
1784 TRUE, // handles are inherited
1785 0, // creation flags
1786 NULL, // use parent's environment
1787 NULL, // use parent's current directory
1788 &siStartInfo, // STARTUPINFO pointer
1789 &piProcInfo); // receives PROCESS_INFORMATION
1791 if (bFuncRetn == 0) {
1792 ErrorExit("CreateProcess failed\n");
1793 const char *err = errorString();
1794 Dmsg3(99, "CreateProcess(%s, %s, ...)=%s\n", comspec, cmdLine, err);
1795 LocalFree((void *)err);
1796 return INVALID_HANDLE_VALUE;
1798 // we don't need a handle on the process primary thread so we close
1800 CloseHandle(piProcInfo.hThread);
1802 return piProcInfo.hProcess;
1807 ErrorExit (LPCSTR lpszMessage)
1809 Dmsg1(0, "%s", lpszMessage);
1814 typedef struct s_bpipe {
1816 time_t worker_stime;
1825 CloseIfValid(HANDLE handle)
1827 if (handle != INVALID_HANDLE_VALUE)
1828 CloseHandle(handle);
1832 open_bpipe(char *prog, int wait, const char *mode)
1834 HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
1835 hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup,
1838 SECURITY_ATTRIBUTES saAttr;
1842 hChildStdinRd = hChildStdinWr = hChildStdinWrDup =
1843 hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup =
1844 hInputFile = INVALID_HANDLE_VALUE;
1846 BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
1847 memset((void *)bpipe, 0, sizeof(BPIPE));
1849 int mode_read = (mode[0] == 'r');
1850 int mode_write = (mode[0] == 'w' || mode[1] == 'w');
1853 // Set the bInheritHandle flag so pipe handles are inherited.
1855 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1856 saAttr.bInheritHandle = TRUE;
1857 saAttr.lpSecurityDescriptor = NULL;
1861 // Create a pipe for the child process's STDOUT.
1862 if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
1863 ErrorExit("Stdout pipe creation failed\n");
1866 // Create noninheritable read handle and close the inheritable read
1869 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
1870 GetCurrentProcess(), &hChildStdoutRdDup , 0,
1872 DUPLICATE_SAME_ACCESS);
1874 ErrorExit("DuplicateHandle failed");
1878 CloseHandle(hChildStdoutRd);
1879 hChildStdoutRd = INVALID_HANDLE_VALUE;
1884 // Create a pipe for the child process's STDIN.
1886 if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
1887 ErrorExit("Stdin pipe creation failed\n");
1891 // Duplicate the write handle to the pipe so it is not inherited.
1892 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
1893 GetCurrentProcess(), &hChildStdinWrDup,
1895 FALSE, // not inherited
1896 DUPLICATE_SAME_ACCESS);
1898 ErrorExit("DuplicateHandle failed");
1902 CloseHandle(hChildStdinWr);
1903 hChildStdinWr = INVALID_HANDLE_VALUE;
1905 // spawn program with redirected handles as appropriate
1906 bpipe->worker_pid = (pid_t)
1907 CreateChildProcess(prog, // commandline
1908 hChildStdinRd, // stdin HANDLE
1909 hChildStdoutWr, // stdout HANDLE
1910 hChildStdoutWr); // stderr HANDLE
1912 if ((HANDLE) bpipe->worker_pid == INVALID_HANDLE_VALUE)
1916 bpipe->worker_stime = time(NULL);
1919 CloseHandle(hChildStdoutWr); // close our write side so when
1920 // process terminates we can
1922 // ugly but convert WIN32 HANDLE to FILE*
1923 int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
1925 bpipe->rfd = _fdopen(rfd, "r");
1929 CloseHandle(hChildStdinRd); // close our read side so as not
1930 // to interfre with child's copy
1931 // ugly but convert WIN32 HANDLE to FILE*
1932 int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
1934 bpipe->wfd = _fdopen(wfd, "w");
1939 bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
1946 CloseIfValid(hChildStdoutRd);
1947 CloseIfValid(hChildStdoutRdDup);
1948 CloseIfValid(hChildStdinWr);
1949 CloseIfValid(hChildStdinWrDup);
1951 free((void *) bpipe);
1952 errno = b_errno_win32; /* do GetLastError() for error code */
1958 kill(int pid, int signal)
1961 if (!TerminateProcess((HANDLE)pid, (UINT) signal)) {
1963 errno = b_errno_win32;
1965 CloseHandle((HANDLE)pid);
1971 close_bpipe(BPIPE *bpipe)
1974 int32_t remaining_wait = bpipe->wait;
1976 if (remaining_wait == 0) { /* wait indefinitely */
1977 remaining_wait = INT32_MAX;
1981 if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode)) {
1982 const char *err = errorString();
1983 rval = b_errno_win32;
1984 Dmsg1(0, "GetExitCode error %s\n", err);
1985 LocalFree((void *)err);
1988 if (exitCode == STILL_ACTIVE) {
1989 if (remaining_wait <= 0) {
1990 rval = ETIME; /* timed out */
1993 bmicrosleep(1, 0); /* wait one second */
1995 } else if (exitCode != 0) {
1996 /* Truncate exit code as it doesn't seem to be correct */
1997 rval = (exitCode & 0xFF) | b_errno_exit;
2000 break; /* Shouldn't get here */
2004 if (bpipe->timer_id) {
2005 stop_child_timer(bpipe->timer_id);
2007 if (bpipe->rfd) fclose(bpipe->rfd);
2008 if (bpipe->wfd) fclose(bpipe->wfd);
2009 free((void *)bpipe);
2014 close_wpipe(BPIPE *bpipe)
2020 if (fclose(bpipe->wfd) != 0) {
2028 #include "findlib/find.h"
2031 utime(const char *fname, struct utimbuf *times)
2036 conv_unix_to_win32_path(fname, tmpbuf, 5000);
2038 cvt_utime_to_ftime(times->actime, acc);
2039 cvt_utime_to_ftime(times->modtime, mod);
2041 HANDLE h = INVALID_HANDLE_VALUE;
2043 if (p_CreateFileW) {
2044 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
2045 make_win32_path_UTF8_2_wchar(&pwszBuf, tmpbuf);
2047 h = p_CreateFileW((LPCWSTR)pwszBuf,
2048 FILE_WRITE_ATTRIBUTES,
2049 FILE_SHARE_WRITE|FILE_SHARE_READ|FILE_SHARE_DELETE,
2052 FILE_FLAG_BACKUP_SEMANTICS, // required for directories
2055 free_pool_memory(pwszBuf);
2056 } else if (p_CreateFileA) {
2057 h = p_CreateFileA(tmpbuf,
2058 FILE_WRITE_ATTRIBUTES,
2059 FILE_SHARE_WRITE|FILE_SHARE_READ|FILE_SHARE_DELETE,
2062 FILE_FLAG_BACKUP_SEMANTICS, // required for directories
2066 if (h == INVALID_HANDLE_VALUE) {
2067 const char *err = errorString();
2068 Dmsg2(99, "Cannot open file \"%s\" for utime(): ERR=%s", tmpbuf, err);
2069 LocalFree((void *)err);
2070 errno = b_errno_win32;
2074 int rval = SetFileTime(h, NULL, &acc, &mod) ? 0 : -1;
2077 errno = b_errno_win32;
2084 file_open(const char *file, int flags, int mode)
2087 DWORD shareMode = 0;
2090 HANDLE foo = INVALID_HANDLE_VALUE;
2091 const char *remap = file;
2093 if (flags & O_WRONLY) access = GENERIC_WRITE;
2094 else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
2095 else access = GENERIC_READ;
2097 if ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
2098 create = CREATE_NEW;
2099 else if ((flags & (O_CREAT | O_TRUNC)) == (O_CREAT | O_TRUNC))
2100 create = CREATE_ALWAYS;
2101 else if (flags & O_CREAT)
2102 create = OPEN_ALWAYS;
2103 else if (flags & O_TRUNC)
2104 create = TRUNCATE_EXISTING;
2106 create = OPEN_EXISTING;
2110 if (flags & O_APPEND) {
2111 printf("open...APPEND not implemented yet.");
2115 if (p_CreateFileW) {
2116 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
2117 make_win32_path_UTF8_2_wchar(&pwszBuf, file);
2119 foo = p_CreateFileW((LPCWSTR) pwszBuf, access, shareMode, NULL, create, msflags, NULL);
2120 free_pool_memory(pwszBuf);
2121 } else if (p_CreateFileA)
2122 foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
2124 if (INVALID_HANDLE_VALUE == foo) {
2125 errno = b_errno_win32;
2136 if (!CloseHandle((HANDLE)fd)) {
2137 errno = b_errno_win32;
2145 file_write(int fd, const void *data, ssize_t len)
2149 status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
2150 if (status) return bwrite;
2151 errno = b_errno_win32;
2157 file_read(int fd, void *data, ssize_t len)
2162 status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
2163 if (status) return bread;
2164 errno = b_errno_win32;
2169 file_seek(int fd, off_t offset, int whence)
2175 method = FILE_BEGIN;
2178 method = FILE_CURRENT;
2188 if ((val=SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method)) == INVALID_SET_FILE_POINTER) {
2189 errno = b_errno_win32;
2192 /* ***FIXME*** I doubt this works right */
2205 /* syslog function, added by Nicolas Boichat */
2206 void openlog(const char *ident, int option, int facility) {}