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)
31 /* UTF-8 to UCS2 path conversion is expensive,
32 so we cache the conversion. During backup the
33 conversion is called 3 times (lstat, attribs, open),
34 by using the cache this is reduced to 1 time */
36 static POOLMEM *g_pWin32ConvUTF8Cache = get_pool_memory (PM_FNAME);
37 static POOLMEM *g_pWin32ConvUCS2Cache = get_pool_memory (PM_FNAME);
38 static DWORD g_dwWin32ConvUTF8strlen = 0;
39 static pthread_mutex_t Win32Convmutex = PTHREAD_MUTEX_INITIALIZER;
41 static t_pVSSPathConvert g_pVSSPathConvert;
42 static t_pVSSPathConvertW g_pVSSPathConvertW;
44 void SetVSSPathConvert(t_pVSSPathConvert pPathConvert, t_pVSSPathConvertW pPathConvertW)
46 g_pVSSPathConvert = pPathConvert;
47 g_pVSSPathConvertW = pPathConvertW;
50 void Win32ConvCleanupCache()
52 if (g_pWin32ConvUTF8Cache) {
53 free_pool_memory(g_pWin32ConvUTF8Cache);
54 g_pWin32ConvUTF8Cache = NULL;
57 if (g_pWin32ConvUCS2Cache) {
58 free_pool_memory(g_pWin32ConvUCS2Cache);
59 g_pWin32ConvUCS2Cache = NULL;
62 g_dwWin32ConvUTF8strlen = 0;
66 /* to allow the usage of the original version in this file here */
70 //#define USE_WIN32_COMPAT_IO 1
71 #define USE_WIN32_32KPATHCONVERSION 1
73 extern void d_msg(const char *file, int line, int level, const char *fmt,...);
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 if ((name[0] == '/' || name[0] == '\\') &&
92 (name[1] == '/' || name[1] == '\\') &&
94 (name[3] == '/' || name[3] == '\\')) {
105 /* Check for Unix separator and convert to Win32 */
106 if (name[0] == '/' && name[1] == '/') { /* double slash? */
107 name++; /* yes, skip first one */
110 *win32_name++ = '\\'; /* convert char */
111 /* If Win32 separated that is "quoted", remove quote */
112 } else if (*name == '\\' && name[1] == '\\') {
113 *win32_name++ = '\\';
114 name++; /* skip first \ */
116 *win32_name++ = *name; /* copy character */
120 /* Strip any trailing slash, if we stored something */
121 /* but leave "c:\" with backslash (root directory case */
122 if (*fname != 0 && win32_name[-1] == '\\' && strlen (fname) != 3) {
128 /* here we convert to VSS specific file name which
129 can get longer because VSS will make something like
130 \\\\?\\GLOBALROOT\\Device\\HarddiskVolumeShadowCopy1\\bacula\\uninstall.exe
131 from c:\bacula\uninstall.exe
133 if (g_pVSSPathConvert != NULL) {
134 POOLMEM *pszBuf = get_pool_memory (PM_FNAME);
135 pszBuf = check_pool_memory_size(pszBuf, dwSize);
136 bstrncpy(pszBuf, tname, strlen(tname)+1);
137 g_pVSSPathConvert(pszBuf, tname, dwSize);
138 free_pool_memory(pszBuf);
142 /* Conversion of a Unix filename to a Win32 filename */
143 void unix_name_to_win32(POOLMEM **win32_name, char *name)
145 /* One extra byte should suffice, but we double it */
146 /* add MAX_PATH bytes for VSS shadow copy name */
147 DWORD dwSize = 2*strlen(name)+MAX_PATH;
148 *win32_name = check_pool_memory_size(*win32_name, dwSize);
149 conv_unix_to_win32_path(name, *win32_name, dwSize);
153 make_wchar_win32_path(POOLMEM *pszUCSPath, BOOL *pBIsRawPath /*= NULL*/)
155 /* created 02/27/2006 Thorsten Engel
157 This function expects an UCS-encoded standard wchar_t in pszUCSPath and
158 will complete the input path to an absolue path of the form \\?\c:\path\file
160 With this trick, it is possible to have 32K characters long paths.
162 Optionally one can use pBIsRawPath to determine id pszUCSPath contains a path
163 to a raw windows partition */
166 *pBIsRawPath = FALSE;
168 if (!p_GetCurrentDirectoryW)
171 wchar_t *name = (wchar_t *) pszUCSPath;
173 /* if it has already the desired form, exit without changes */
174 if (wcslen(name) > 3 && wcsncmp(name, L"\\\\?\\", 4) == 0)
177 POOLMEM *pwszBuf = get_pool_memory(PM_FNAME);
178 POOLMEM *pwszCurDirBuf = get_pool_memory(PM_FNAME);
179 DWORD dwCurDirPathSize = 0;
181 /* get buffer with enough size (name+max 6. wchars+1 null terminator */
182 DWORD dwBufCharsNeeded = (wcslen(name)+7);
183 pwszBuf = check_pool_memory_size(pwszBuf, dwBufCharsNeeded*sizeof(wchar_t));
185 /* add \\?\ to support 32K long filepaths
186 it is important to make absolute paths, so we add drive and
187 current path if necessary */
189 BOOL bAddDrive = TRUE;
190 BOOL bAddCurrentPath = TRUE;
191 BOOL bAddPrefix = TRUE;
193 /* does path begin with drive? if yes, it is absolute */
194 if (wcslen(name) >= 3 && (iswalpha (*name) && *(name+1) == ':'
195 && (*(name+2) == '\\' || *(name+2) == '/'))) {
197 bAddCurrentPath = FALSE;
200 /* is path absolute? */
201 if (*name == '/' || *name == '\\')
202 bAddCurrentPath = FALSE;
204 /* is path relative to itself?, if yes, skip ./ */
205 if (wcslen(name) > 2 && ((wcsncmp(name, L"./", 2) == 0) || (wcsncmp(name, L".\\", 2) == 0))) {
209 /* is path of form '//./'? */
210 if (wcslen(name) > 3 && ((wcsncmp(name, L"//./", 4) == 0) || (wcsncmp(name, L"\\\\.\\", 4) == 0))) {
212 bAddCurrentPath = FALSE;
218 int nParseOffset = 0;
220 /* add 4 bytes header */
223 wcscpy ((wchar_t *) pwszBuf,L"\\\\?\\");
226 /* get current path if needed */
227 if (bAddDrive || bAddCurrentPath) {
228 dwCurDirPathSize = p_GetCurrentDirectoryW(0, NULL);
229 if (dwCurDirPathSize > 0) {
230 /* get directory into own buffer as it may either return c:\... or \\?\C:\.... */
231 pwszCurDirBuf = check_pool_memory_size(pwszCurDirBuf, (dwCurDirPathSize+1)*sizeof(wchar_t));
232 p_GetCurrentDirectoryW(dwCurDirPathSize,(wchar_t *)pwszCurDirBuf);
236 /* we have no info for doing so */
238 bAddCurrentPath = FALSE;
243 /* add drive if needed */
244 if (bAddDrive && !bAddCurrentPath) {
247 if (dwCurDirPathSize > 3 && wcsncmp((LPCWSTR)pwszCurDirBuf, L"\\\\?\\", 4) == 0)
248 /* copy drive character */
249 wcsncpy((wchar_t *) szDrive, (LPCWSTR)pwszCurDirBuf+4,2);
251 /* copy drive character */
252 wcsncpy((wchar_t *) szDrive, (LPCWSTR)pwszCurDirBuf,2);
256 wcscat((wchar_t *) pwszBuf, szDrive);
260 /* add path if needed */
261 if (bAddCurrentPath) {
262 /* the 1 add. character is for the eventually added backslash */
263 dwBufCharsNeeded += dwCurDirPathSize+1;
264 pwszBuf = check_pool_memory_size(pwszBuf, dwBufCharsNeeded*sizeof(wchar_t));
265 /* get directory into own buffer as it may either return c:\... or \\?\C:\.... */
267 if (dwCurDirPathSize > 3 && wcsncmp((LPCWSTR)pwszCurDirBuf, L"\\\\?\\", 4) == 0)
268 /* copy complete string */
269 wcscpy((wchar_t *) pwszBuf, (LPCWSTR)pwszCurDirBuf);
272 wcscat((wchar_t *) pwszBuf, (LPCWSTR)pwszCurDirBuf);
274 nParseOffset = wcslen ((LPCWSTR) pwszBuf);
276 /* check if path ends with backslash, if not, add one */
277 if (*((wchar_t *) pwszBuf+nParseOffset-1) != L'\\') {
278 wcscat((wchar_t *) pwszBuf, L"\\");
284 wchar_t *win32_name = (wchar_t *)pwszBuf+nParseOffset;
287 /* Check for Unix separator and convert to Win32 */
289 *win32_name++ = '\\'; /* convert char */
290 /* If Win32 separated that is "quoted", remove quote */
291 /* HELPME (Thorsten Engel): I don't understand the following part
292 and it removes a backslash from e.g. "\\.\c:" which I need for
293 RAW device access. So I took it out */
294 /* } else if (*name == '\\' && name[1] == '\\') {
295 *win32_name++ = '\\';
296 name++; */ /* skip first \ */
298 *win32_name++ = *name; /* copy character */
303 /* null terminate string */
306 /* here we convert to VSS specific file name which
307 can get longer because VSS will make something like
308 \\\\?\\GLOBALROOT\\Device\\HarddiskVolumeShadowCopy1\\bacula\\uninstall.exe
309 from c:\bacula\uninstall.exe
311 if (g_pVSSPathConvertW != NULL) {
312 /* is output buffer large enough? */
313 pwszBuf = check_pool_memory_size(pwszBuf, (dwBufCharsNeeded+MAX_PATH)*sizeof(wchar_t));
314 /* create temp. buffer */
315 POOLMEM* pszBuf = get_pool_memory(PM_FNAME);
316 pszBuf = check_pool_memory_size(pszBuf, (dwBufCharsNeeded+MAX_PATH)*sizeof(wchar_t));
321 wcsncpy((wchar_t *) pszBuf, (wchar_t *) pwszBuf+nParseOffset, wcslen((wchar_t *)pwszBuf)+1-nParseOffset);
322 g_pVSSPathConvertW((wchar_t *)pszBuf,(wchar_t *)pwszBuf,dwBufCharsNeeded+MAX_PATH);
323 free_pool_memory(pszBuf);
326 free_pool_memory(pszUCSPath);
327 free_pool_memory(pwszCurDirBuf);
333 wchar_2_UTF8(char *pszUTF, const wchar_t *pszUCS, int cchChar)
335 /* the return value is the number of bytes written to the buffer.
336 The number includes the byte for the null terminator. */
338 if (p_WideCharToMultiByte) {
339 int nRet = p_WideCharToMultiByte(CP_UTF8,0,pszUCS,-1,pszUTF,cchChar,NULL,NULL);
348 UTF8_2_wchar(POOLMEM **ppszUCS, const char *pszUTF)
350 /* the return value is the number of wide characters written to the buffer. */
351 /* convert null terminated string from utf-8 to ucs2, enlarge buffer if necessary */
353 if (p_MultiByteToWideChar) {
354 /* strlen of UTF8 +1 is enough */
355 DWORD cchSize = (strlen(pszUTF)+1);
356 *ppszUCS = check_pool_memory_size(*ppszUCS, cchSize*sizeof (wchar_t));
358 int nRet = p_MultiByteToWideChar(CP_UTF8, 0, pszUTF, -1, (LPWSTR) *ppszUCS,cchSize);
368 wchar_win32_path(const char *name, wchar_t *win32_name)
370 const char *fname = name;
372 /* Check for Unix separator and convert to Win32 */
374 *win32_name++ = '\\'; /* convert char */
375 /* If Win32 separated that is "quoted", remove quote */
376 } else if (*name == '\\' && name[1] == '\\') {
377 *win32_name++ = '\\';
378 name++; /* skip first \ */
380 *win32_name++ = *name; /* copy character */
384 /* Strip any trailing slash, if we stored something */
385 if (*fname != 0 && win32_name[-1] == '\\') {
393 make_win32_path_UTF8_2_wchar(POOLMEM **pszUCS, const char *pszUTF, BOOL* pBIsRawPath /*= NULL*/)
396 /* if we find the utf8 string in cache, we use the cached ucs2 version.
397 we compare the stringlength first (quick check) and then compare the content.
399 if (g_dwWin32ConvUTF8strlen == strlen(pszUTF)) {
400 if (bstrcmp(pszUTF, g_pWin32ConvUTF8Cache)) {
401 int32_t nBufSize = sizeof_pool_memory(g_pWin32ConvUCS2Cache);
402 *pszUCS = check_pool_memory_size(*pszUCS, nBufSize);
403 wcscpy((LPWSTR) *pszUCS, (LPWSTR) g_pWin32ConvUCS2Cache);
405 return nBufSize / sizeof (WCHAR);
409 /* helper to convert from utf-8 to UCS-2 and to complete a path for 32K path syntax */
410 int nRet = UTF8_2_wchar(pszUCS, pszUTF);
412 #ifdef USE_WIN32_32KPATHCONVERSION
413 /* add \\?\ to support 32K long filepaths */
414 *pszUCS = make_wchar_win32_path(*pszUCS, pBIsRawPath);
417 *pBIsRawPath = FALSE;
421 g_pWin32ConvUCS2Cache = check_pool_memory_size(g_pWin32ConvUCS2Cache, sizeof_pool_memory(*pszUCS));
422 wcscpy((LPWSTR) g_pWin32ConvUCS2Cache, (LPWSTR) *pszUCS);
424 g_dwWin32ConvUTF8strlen = strlen(pszUTF);
425 g_pWin32ConvUTF8Cache = check_pool_memory_size(g_pWin32ConvUTF8Cache, g_dwWin32ConvUTF8strlen+1);
426 bstrncpy(g_pWin32ConvUTF8Cache, pszUTF, g_dwWin32ConvUTF8strlen+1);
432 #if !defined(_MSC_VER) || (_MSC_VER < 1400) // VC8+
439 int fcntl(int fd, int cmd)
444 int chmod(const char *, mode_t)
449 int chown(const char *k, uid_t, gid_t)
454 int lchown(const char *k, uid_t, gid_t)
466 srandom(unsigned int seed)
470 // /////////////////////////////////////////////////////////////////
471 // convert from Windows concept of time to Unix concept of time
472 // /////////////////////////////////////////////////////////////////
474 cvt_utime_to_ftime(const time_t &time, FILETIME &wintime)
476 uint64_t mstime = time;
477 mstime *= WIN32_FILETIME_SCALE;
478 mstime += WIN32_FILETIME_ADJUST;
480 #if defined(_MSC_VER)
481 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffI64);
483 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffUL);
485 wintime.dwHighDateTime = (DWORD) ((mstime>>32)& 0xffffffffUL);
489 cvt_ftime_to_utime(const FILETIME &time)
491 uint64_t mstime = time.dwHighDateTime;
493 mstime |= time.dwLowDateTime;
495 mstime -= WIN32_FILETIME_ADJUST;
496 mstime /= WIN32_FILETIME_SCALE; // convert to seconds.
498 return (time_t) (mstime & 0xffffffff);
506 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
507 FORMAT_MESSAGE_FROM_SYSTEM |
508 FORMAT_MESSAGE_IGNORE_INSERTS,
511 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default lang
516 /* Strip any \r or \n */
517 char *rval = (char *) lpMsgBuf;
518 char *cp = strchr(rval, '\r');
522 cp = strchr(rval, '\n');
531 statDir(const char *file, struct stat *sb)
533 WIN32_FIND_DATAW info_w; // window's file info
534 WIN32_FIND_DATAA info_a; // window's file info
536 // cache some common vars to make code more transparent
537 DWORD* pdwFileAttributes;
538 DWORD* pnFileSizeHigh;
539 DWORD* pnFileSizeLow;
540 FILETIME* pftLastAccessTime;
541 FILETIME* pftLastWriteTime;
542 FILETIME* pftCreationTime;
544 if (file[1] == ':' && file[2] == 0) {
545 d_msg(__FILE__, __LINE__, 99, "faking ROOT attrs(%s).\n", file);
546 sb->st_mode = S_IFDIR;
547 sb->st_mode |= S_IREAD|S_IEXEC|S_IWRITE;
554 HANDLE h = INVALID_HANDLE_VALUE;
556 // use unicode or ascii
557 if (p_FindFirstFileW) {
558 POOLMEM* pwszBuf = get_pool_memory (PM_FNAME);
559 make_win32_path_UTF8_2_wchar(&pwszBuf, file);
561 h = p_FindFirstFileW((LPCWSTR) pwszBuf, &info_w);
562 free_pool_memory(pwszBuf);
564 pdwFileAttributes = &info_w.dwFileAttributes;
565 pnFileSizeHigh = &info_w.nFileSizeHigh;
566 pnFileSizeLow = &info_w.nFileSizeLow;
567 pftLastAccessTime = &info_w.ftLastAccessTime;
568 pftLastWriteTime = &info_w.ftLastWriteTime;
569 pftCreationTime = &info_w.ftCreationTime;
571 else if (p_FindFirstFileA) {
572 h = p_FindFirstFileA(file, &info_a);
574 pdwFileAttributes = &info_a.dwFileAttributes;
575 pnFileSizeHigh = &info_a.nFileSizeHigh;
576 pnFileSizeLow = &info_a.nFileSizeLow;
577 pftLastAccessTime = &info_a.ftLastAccessTime;
578 pftLastWriteTime = &info_a.ftLastWriteTime;
579 pftCreationTime = &info_a.ftCreationTime;
582 if (h == INVALID_HANDLE_VALUE) {
583 const char *err = errorString();
584 d_msg(__FILE__, __LINE__, 99, "FindFirstFile(%s):%s\n", file, err);
585 LocalFree((void *)err);
586 errno = b_errno_win32;
590 sb->st_mode = 0777; /* start with everything */
591 if (*pdwFileAttributes & FILE_ATTRIBUTE_READONLY)
592 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
593 if (*pdwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
594 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
595 if (*pdwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
596 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
597 sb->st_mode |= S_IFDIR;
599 sb->st_size = *pnFileSizeHigh;
601 sb->st_size |= *pnFileSizeLow;
602 sb->st_blksize = 4096;
603 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
605 sb->st_atime = cvt_ftime_to_utime(*pftLastAccessTime);
606 sb->st_mtime = cvt_ftime_to_utime(*pftLastWriteTime);
607 sb->st_ctime = cvt_ftime_to_utime(*pftCreationTime);
614 fstat(int fd, struct stat *sb)
616 BY_HANDLE_FILE_INFORMATION info;
619 if (!GetFileInformationByHandle((HANDLE)fd, &info)) {
620 const char *err = errorString();
621 d_msg(__FILE__, __LINE__, 99,
622 "GetfileInformationByHandle(%s): %s\n", tmpbuf, err);
623 LocalFree((void *)err);
624 errno = b_errno_win32;
628 sb->st_dev = info.dwVolumeSerialNumber;
629 sb->st_ino = info.nFileIndexHigh;
631 sb->st_ino |= info.nFileIndexLow;
632 sb->st_nlink = (short)info.nNumberOfLinks;
633 if (sb->st_nlink > 1) {
634 d_msg(__FILE__, __LINE__, 99, "st_nlink=%d\n", sb->st_nlink);
637 sb->st_mode = 0777; /* start with everything */
638 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
639 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
640 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
641 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
642 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
643 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
644 sb->st_mode |= S_IFREG;
646 sb->st_size = info.nFileSizeHigh;
648 sb->st_size |= info.nFileSizeLow;
649 sb->st_blksize = 4096;
650 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
651 sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
652 sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
653 sb->st_ctime = cvt_ftime_to_utime(info.ftCreationTime);
659 stat2(const char *file, struct stat *sb)
664 conv_unix_to_win32_path(file, tmpbuf, 1024);
666 DWORD attr = (DWORD)-1;
668 if (p_GetFileAttributesW) {
669 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
670 make_win32_path_UTF8_2_wchar(&pwszBuf, tmpbuf);
672 attr = p_GetFileAttributesW((LPCWSTR) pwszBuf);
673 free_pool_memory(pwszBuf);
674 } else if (p_GetFileAttributesA) {
675 attr = p_GetFileAttributesA(tmpbuf);
678 if (attr == (DWORD)-1) {
679 const char *err = errorString();
680 d_msg(__FILE__, __LINE__, 99,
681 "GetFileAttributes(%s): %s\n", tmpbuf, err);
682 LocalFree((void *)err);
683 errno = b_errno_win32;
687 if (attr & FILE_ATTRIBUTE_DIRECTORY)
688 return statDir(tmpbuf, sb);
690 h = CreateFileA(tmpbuf, GENERIC_READ,
691 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
693 if (h == INVALID_HANDLE_VALUE) {
694 const char *err = errorString();
695 d_msg(__FILE__, __LINE__, 99,
696 "Cannot open file for stat (%s):%s\n", tmpbuf, err);
697 LocalFree((void *)err);
698 errno = b_errno_win32;
702 rval = fstat((int)h, sb);
709 stat(const char *file, struct stat *sb)
711 WIN32_FILE_ATTRIBUTE_DATA data;
715 memset(sb, 0, sizeof(*sb));
717 /* why not allow win 95 to use p_GetFileAttributesExA ?
718 * this function allows _some_ open files to be stat'ed
719 * if (g_platform_id == VER_PLATFORM_WIN32_WINDOWS) {
720 * return stat2(file, sb);
724 if (p_GetFileAttributesExW) {
725 /* dynamically allocate enough space for UCS2 filename */
726 POOLMEM* pwszBuf = get_pool_memory (PM_FNAME);
727 make_win32_path_UTF8_2_wchar(&pwszBuf, file);
729 BOOL b = p_GetFileAttributesExW((LPCWSTR) pwszBuf, GetFileExInfoStandard, &data);
730 free_pool_memory(pwszBuf);
733 return stat2(file, sb);
735 } else if (p_GetFileAttributesExA) {
736 if (!p_GetFileAttributesExA(file, GetFileExInfoStandard, &data)) {
737 return stat2(file, sb);
740 return stat2(file, sb);
743 sb->st_mode = 0777; /* start with everything */
744 if (data.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
745 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
747 if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
748 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
750 if (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
751 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
753 if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
754 sb->st_mode |= S_IFDIR;
756 sb->st_mode |= S_IFREG;
760 sb->st_size = data.nFileSizeHigh;
762 sb->st_size |= data.nFileSizeLow;
763 sb->st_blksize = 4096;
764 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
765 sb->st_atime = cvt_ftime_to_utime(data.ftLastAccessTime);
766 sb->st_mtime = cvt_ftime_to_utime(data.ftLastWriteTime);
767 sb->st_ctime = cvt_ftime_to_utime(data.ftCreationTime);
771 int fcntl(int fd, int cmd, long arg)
794 lstat(const char *file, struct stat *sb)
796 return stat(file, sb);
812 execvp(const char *, char *[]) {
833 waitpid(int, int*, int)
840 readlink(const char *, char *, int)
849 strcasecmp(const char *s1, const char *s2)
851 register int ch1, ch2;
854 return 0; /* strings are equal if same object. */
864 } while (ch1 != 0 && tolower(ch1) == tolower(ch2));
871 strncasecmp(const char *s1, const char *s2, int len)
873 register int ch1 = 0, ch2 = 0;
876 return 0; /* strings are equal if same object. */
887 if (ch1 == 0 || tolower(ch1) != tolower(ch2)) break;
894 gettimeofday(struct timeval *tv, struct timezone *)
904 if (!SystemTimeToFileTime(&now, &tmp)) {
905 errno = b_errno_win32;
909 int64_t _100nsec = tmp.dwHighDateTime;
911 _100nsec |= tmp.dwLowDateTime;
912 _100nsec -= WIN32_FILETIME_ADJUST;
914 tv->tv_sec =(long) (_100nsec / 10000000);
915 tv->tv_usec = (long) ((_100nsec % 10000000)/10);
920 /* For apcupsd this is in src/lib/wincompat.c */
921 extern "C" void syslog(int type, const char *fmt, ...)
923 /*#ifndef HAVE_CONSOLE
924 MessageBox(NULL, msg, "Bacula", MB_OK);
945 // implement opendir/readdir/closedir on top of window's API
949 WIN32_FIND_DATAA data_a; // window's file info (ansii version)
950 WIN32_FIND_DATAW data_w; // window's file info (wchar version)
951 const char *spec; // the directory we're traversing
952 HANDLE dirh; // the search handle
953 BOOL valid_a; // the info in data_a field is valid
954 BOOL valid_w; // the info in data_w field is valid
955 UINT32 offset; // pseudo offset for d_off
959 opendir(const char *path)
961 /* enough space for VSS !*/
962 int max_len = strlen(path) + MAX_PATH;
969 rval = (_dir *)malloc(sizeof(_dir));
970 memset (rval, 0, sizeof (_dir));
971 if (rval == NULL) return NULL;
972 char *tspec = (char *)malloc(max_len);
973 if (tspec == NULL) return NULL;
975 if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS) {
977 /* will append \\?\ at front itself */
978 conv_unix_to_win32_path(path, tspec, max_len-4);
980 /* allow path to be 32767 bytes */
986 conv_unix_to_win32_path(path, tspec+4, max_len-4);
989 conv_unix_to_win32_path(path, tspec, max_len);
992 // add backslash only if there is none yet (think of c:\)
993 if (tspec[strlen(tspec)-1] != '\\')
994 bstrncat(tspec, "\\*", max_len);
996 bstrncat(tspec, "*", max_len);
1000 // convert to wchar_t
1001 if (p_FindFirstFileW) {
1002 POOLMEM* pwcBuf = get_pool_memory(PM_FNAME);;
1003 make_win32_path_UTF8_2_wchar(&pwcBuf,rval->spec);
1005 rval->dirh = p_FindFirstFileW((LPCWSTR)pwcBuf, &rval->data_w);
1007 free_pool_memory(pwcBuf);
1009 if (rval->dirh != INVALID_HANDLE_VALUE)
1011 } else if (p_FindFirstFileA) {
1012 rval->dirh = p_FindFirstFileA(rval->spec, &rval->data_a);
1014 if (rval->dirh != INVALID_HANDLE_VALUE)
1019 d_msg(__FILE__, __LINE__,
1020 99, "opendir(%s)\n\tspec=%s,\n\tFindFirstFile returns %d\n",
1021 path, rval->spec, rval->dirh);
1024 if (rval->dirh == INVALID_HANDLE_VALUE)
1028 d_msg(__FILE__, __LINE__,
1029 99, "\tFirstFile=%s\n", rval->data_w.cFileName);
1032 d_msg(__FILE__, __LINE__,
1033 99, "\tFirstFile=%s\n", rval->data_a.cFileName);
1038 free((void *)rval->spec);
1040 errno = b_errno_win32;
1047 _dir *dp = (_dir *)dirp;
1048 FindClose(dp->dirh);
1049 free((void *)dp->spec);
1055 typedef struct _WIN32_FIND_DATA {
1056 DWORD dwFileAttributes;
1057 FILETIME ftCreationTime;
1058 FILETIME ftLastAccessTime;
1059 FILETIME ftLastWriteTime;
1060 DWORD nFileSizeHigh;
1064 TCHAR cFileName[MAX_PATH];
1065 TCHAR cAlternateFileName[14];
1066 } WIN32_FIND_DATA, *PWIN32_FIND_DATA;
1070 copyin(struct dirent &dp, const char *fname)
1074 char *cp = dp.d_name;
1084 readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
1086 _dir *dp = (_dir *)dirp;
1087 if (dp->valid_w || dp->valid_a) {
1088 entry->d_off = dp->offset;
1092 char szBuf[MAX_PATH_UTF8+1];
1093 wchar_2_UTF8(szBuf,dp->data_w.cFileName);
1094 dp->offset += copyin(*entry, szBuf);
1095 } else if (dp->valid_a) { // copy ansi (only 1 will be valid)
1096 dp->offset += copyin(*entry, dp->data_a.cFileName);
1099 *result = entry; /* return entry address */
1100 d_msg(__FILE__, __LINE__,
1101 99, "readdir_r(%p, { d_name=\"%s\", d_reclen=%d, d_off=%d\n",
1102 dirp, entry->d_name, entry->d_reclen, entry->d_off);
1104 // d_msg(__FILE__, __LINE__, 99, "readdir_r !valid\n");
1105 errno = b_errno_win32;
1109 // get next file, try unicode first
1110 if (p_FindNextFileW)
1111 dp->valid_w = p_FindNextFileW(dp->dirh, &dp->data_w);
1112 else if (p_FindNextFileA)
1113 dp->valid_a = p_FindNextFileA(dp->dirh, &dp->data_a);
1115 dp->valid_a = FALSE;
1116 dp->valid_w = FALSE;
1123 * Dotted IP address to network address
1129 inet_aton(const char *a, struct in_addr *inp)
1132 uint32_t acc = 0, tmp = 0;
1135 if (!isdigit(*cp)) { /* first char must be digit */
1136 return 0; /* error */
1140 tmp = (tmp * 10) + (*cp -'0');
1141 } else if (*cp == '.' || *cp == 0) {
1143 return 0; /* error */
1145 acc = (acc << 8) + tmp;
1149 return 0; /* error */
1151 } while (*cp++ != 0);
1152 if (dotc != 4) { /* want 3 .'s plus EOS */
1153 return 0; /* error */
1155 inp->s_addr = htonl(acc); /* store addr in network format */
1160 nanosleep(const struct timespec *req, struct timespec *rem)
1163 rem->tv_sec = rem->tv_nsec = 0;
1164 Sleep((req->tv_sec * 1000) + (req->tv_nsec/100000));
1169 init_signals(void terminate(int sig))
1175 init_stack_dump(void)
1182 pathconf(const char *path, int name)
1186 if (strncmp(path, "\\\\?\\", 4) == 0)
1198 WORD wVersionRequested = MAKEWORD( 1, 1);
1201 int err = WSAStartup(wVersionRequested, &wsaData);
1205 printf("Can not start Windows Sockets\n");
1215 win32_chdir(const char *dir)
1217 if (p_SetCurrentDirectoryW) {
1218 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1219 make_win32_path_UTF8_2_wchar(&pwszBuf, dir);
1221 BOOL b=p_SetCurrentDirectoryW((LPCWSTR)pwszBuf);
1223 free_pool_memory(pwszBuf);
1226 errno = b_errno_win32;
1230 else if (p_SetCurrentDirectoryA) {
1231 if (0 == p_SetCurrentDirectoryA(dir)) {
1232 errno = b_errno_win32;
1242 win32_mkdir(const char *dir)
1245 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1246 make_win32_path_UTF8_2_wchar(&pwszBuf, dir);
1248 int n = p_wmkdir((LPCWSTR)pwszBuf);
1249 free_pool_memory(pwszBuf);
1258 win32_getcwd(char *buf, int maxlen)
1262 if (p_GetCurrentDirectoryW) {
1263 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1264 pwszBuf = check_pool_memory_size (pwszBuf, maxlen*sizeof(wchar_t));
1266 n = p_GetCurrentDirectoryW(maxlen, (LPWSTR) pwszBuf);
1268 n = wchar_2_UTF8 (buf, (wchar_t *)pwszBuf, maxlen)-1;
1269 free_pool_memory(pwszBuf);
1271 } else if (p_GetCurrentDirectoryA)
1272 n = p_GetCurrentDirectoryA(maxlen, buf);
1274 if (n == 0 || n > maxlen) return NULL;
1276 if (n+1 > maxlen) return NULL;
1285 win32_fputs(const char *string, FILE *stream)
1287 /* we use WriteConsoleA / WriteConsoleA
1288 so we can be sure that unicode support works on win32.
1289 with fallback if something fails
1292 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
1293 if (hOut && (hOut != INVALID_HANDLE_VALUE) && p_WideCharToMultiByte &&
1294 p_MultiByteToWideChar && (stream == stdout)) {
1296 POOLMEM* pwszBuf = get_pool_memory(PM_MESSAGE);
1298 DWORD dwCharsWritten;
1301 dwChars = UTF8_2_wchar(&pwszBuf, string);
1303 /* try WriteConsoleW */
1304 if (WriteConsoleW (hOut, pwszBuf, dwChars-1, &dwCharsWritten, NULL)) {
1305 free_pool_memory(pwszBuf);
1306 return dwCharsWritten;
1309 /* convert to local codepage and try WriteConsoleA */
1310 POOLMEM* pszBuf = get_pool_memory(PM_MESSAGE);
1311 pszBuf = check_pool_memory_size(pszBuf, dwChars+1);
1313 dwChars = p_WideCharToMultiByte(GetConsoleOutputCP(),0,(LPCWSTR) pwszBuf,-1,pszBuf,dwChars,NULL,NULL);
1314 free_pool_memory(pwszBuf);
1316 if (WriteConsoleA (hOut, pszBuf, dwChars-1, &dwCharsWritten, NULL)) {
1317 free_pool_memory(pszBuf);
1318 return dwCharsWritten;
1322 return fputs(string, stream);
1326 win32_cgets (char* buffer, int len)
1328 /* we use console ReadConsoleA / ReadConsoleW to be able to read unicode
1329 from the win32 console and fallback if seomething fails */
1331 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
1332 if (hIn && (hIn != INVALID_HANDLE_VALUE) && p_WideCharToMultiByte && p_MultiByteToWideChar) {
1334 wchar_t wszBuf[1024];
1337 /* nt and unicode conversion */
1338 if (ReadConsoleW (hIn, wszBuf, 1024, &dwRead, NULL)) {
1340 /* null terminate at end */
1341 if (wszBuf[dwRead-1] == L'\n') {
1342 wszBuf[dwRead-1] = L'\0';
1346 if (wszBuf[dwRead-1] == L'\r') {
1347 wszBuf[dwRead-1] = L'\0';
1351 wchar_2_UTF8(buffer, wszBuf, len);
1355 /* win 9x and unicode conversion */
1356 if (ReadConsoleA (hIn, szBuf, 1024, &dwRead, NULL)) {
1358 /* null terminate at end */
1359 if (szBuf[dwRead-1] == L'\n') {
1360 szBuf[dwRead-1] = L'\0';
1364 if (szBuf[dwRead-1] == L'\r') {
1365 szBuf[dwRead-1] = L'\0';
1369 /* convert from ansii to wchar_t */
1370 p_MultiByteToWideChar(GetConsoleCP(), 0, szBuf, -1, wszBuf,1024);
1371 /* convert from wchar_t to UTF-8 */
1372 if (wchar_2_UTF8(buffer, wszBuf, len))
1378 if (fgets(buffer, len, stdin))
1385 win32_unlink(const char *filename)
1389 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1390 make_win32_path_UTF8_2_wchar(&pwszBuf, filename);
1392 nRetCode = _wunlink((LPCWSTR) pwszBuf);
1394 /* special case if file is readonly,
1395 we retry but unset attribute before */
1396 if (nRetCode == -1 && errno == EACCES && p_SetFileAttributesW && p_GetFileAttributesW) {
1397 DWORD dwAttr = p_GetFileAttributesW((LPCWSTR)pwszBuf);
1398 if (dwAttr != INVALID_FILE_ATTRIBUTES) {
1399 if (p_SetFileAttributesW((LPCWSTR)pwszBuf, dwAttr & ~FILE_ATTRIBUTE_READONLY)) {
1400 nRetCode = _wunlink((LPCWSTR) pwszBuf);
1401 /* reset to original if it didn't help */
1403 p_SetFileAttributesW((LPCWSTR)pwszBuf, dwAttr);
1407 free_pool_memory(pwszBuf);
1409 nRetCode = _unlink(filename);
1411 /* special case if file is readonly,
1412 we retry but unset attribute before */
1413 if (nRetCode == -1 && errno == EACCES && p_SetFileAttributesA && p_GetFileAttributesA) {
1414 DWORD dwAttr = p_GetFileAttributesA(filename);
1415 if (dwAttr != INVALID_FILE_ATTRIBUTES) {
1416 if (p_SetFileAttributesA(filename, dwAttr & ~FILE_ATTRIBUTE_READONLY)) {
1417 nRetCode = _unlink(filename);
1418 /* reset to original if it didn't help */
1420 p_SetFileAttributesA(filename, dwAttr);
1429 #include "mswinver.h"
1431 char WIN_VERSION_LONG[64];
1432 char WIN_VERSION[32];
1433 char WIN_RAWVERSION[32];
1440 static winver INIT; // cause constructor to be called before main()
1443 winver::winver(void)
1445 const char *version = "";
1446 const char *platform = "";
1447 OSVERSIONINFO osvinfo;
1448 osvinfo.dwOSVersionInfoSize = sizeof(osvinfo);
1450 // Get the current OS version
1451 if (!GetVersionEx(&osvinfo)) {
1452 version = "Unknown";
1453 platform = "Unknown";
1455 const int ver = _mkversion(osvinfo.dwPlatformId,
1456 osvinfo.dwMajorVersion,
1457 osvinfo.dwMinorVersion);
1458 snprintf(WIN_RAWVERSION, sizeof(WIN_RAWVERSION), "Windows %#08x", ver);
1461 case MS_WINDOWS_95: (version = "Windows 95"); break;
1462 case MS_WINDOWS_98: (version = "Windows 98"); break;
1463 case MS_WINDOWS_ME: (version = "Windows ME"); break;
1464 case MS_WINDOWS_NT4:(version = "Windows NT 4.0"); platform = "NT"; break;
1465 case MS_WINDOWS_2K: (version = "Windows 2000");platform = "NT"; break;
1466 case MS_WINDOWS_XP: (version = "Windows XP");platform = "NT"; break;
1467 case MS_WINDOWS_S2003: (version = "Windows Server 2003");platform = "NT"; break;
1468 default: version = WIN_RAWVERSION; break;
1471 bstrncpy(WIN_VERSION_LONG, version, sizeof(WIN_VERSION_LONG));
1472 snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %lu.%lu.%lu",
1473 platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
1476 HANDLE h = CreateFile("G:\\foobar", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
1480 BPIPE *b = open_bpipe("ls -l", 10, "r");
1482 while (!feof(b->rfd)) {
1483 fgets(buf, sizeof(buf), b->rfd);
1489 BOOL CreateChildProcess(VOID);
1490 VOID WriteToPipe(VOID);
1491 VOID ReadFromPipe(VOID);
1492 VOID ErrorExit(LPCSTR);
1493 VOID ErrMsg(LPTSTR, BOOL);
1496 * Check for a quoted path, if an absolute path name is given and it contains
1497 * spaces it will need to be quoted. i.e. "c:/Program Files/foo/bar.exe"
1498 * CreateProcess() says the best way to ensure proper results with executables
1499 * with spaces in path or filename is to quote the string.
1502 getArgv0(const char *cmdline)
1507 for (cp = cmdline; *cp; cp++)
1512 if (!inquote && isspace(*cp))
1517 int len = cp - cmdline;
1518 char *rval = (char *)malloc(len+1);
1532 * OK, so it would seem CreateProcess only handles true executables:
1533 * .com or .exe files.
1534 * So test to see whether we're getting a .bat file and if so grab
1535 * $COMSPEC value and pass batch file to it.
1538 CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err)
1540 static const char *comspec = NULL;
1541 PROCESS_INFORMATION piProcInfo;
1542 STARTUPINFOA siStartInfo;
1543 BOOL bFuncRetn = FALSE;
1545 if (comspec == NULL) {
1546 comspec = getenv("COMSPEC");
1548 if (comspec == NULL) // should never happen
1549 return INVALID_HANDLE_VALUE;
1551 // Set up members of the PROCESS_INFORMATION structure.
1552 ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
1554 // Set up members of the STARTUPINFO structure.
1556 ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
1557 siStartInfo.cb = sizeof(STARTUPINFO);
1558 // setup new process to use supplied handles for stdin,stdout,stderr
1559 // if supplied handles are not used the send a copy of our STD_HANDLE
1561 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
1563 if (in != INVALID_HANDLE_VALUE)
1564 siStartInfo.hStdInput = in;
1566 siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1568 if (out != INVALID_HANDLE_VALUE)
1569 siStartInfo.hStdOutput = out;
1571 siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1572 if (err != INVALID_HANDLE_VALUE)
1573 siStartInfo.hStdError = err;
1575 siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1576 // Create the child process.
1579 int cmdLen = strlen(cmdline) + strlen(comspec) + 16;
1581 char *cmdLine = (char *)alloca(cmdLen);
1583 bstrncpy(exeFile, comspec, sizeof(exeFile));
1584 bstrncpy(cmdLine, comspec, cmdLen);
1585 bstrncat(cmdLine, " /c ", cmdLen);
1586 bstrncat(cmdLine, cmdline, cmdLen);
1588 // try to execute program
1589 bFuncRetn = CreateProcessA(exeFile,
1590 cmdLine, // command line
1591 NULL, // process security attributes
1592 NULL, // primary thread security attributes
1593 TRUE, // handles are inherited
1594 0, // creation flags
1595 NULL, // use parent's environment
1596 NULL, // use parent's current directory
1597 &siStartInfo, // STARTUPINFO pointer
1598 &piProcInfo); // receives PROCESS_INFORMATION
1600 if (bFuncRetn == 0) {
1601 ErrorExit("CreateProcess failed\n");
1602 const char *err = errorString();
1603 d_msg(__FILE__, __LINE__, 99,
1604 "CreateProcess(%s, %s, ...)=%s\n", exeFile, cmdLine, err);
1605 LocalFree((void *)err);
1606 return INVALID_HANDLE_VALUE;
1608 // we don't need a handle on the process primary thread so we close
1610 CloseHandle(piProcInfo.hThread);
1612 return piProcInfo.hProcess;
1617 ErrorExit (LPCSTR lpszMessage)
1619 d_msg(__FILE__, __LINE__, 0, "%s", lpszMessage);
1624 typedef struct s_bpipe {
1626 time_t worker_stime;
1635 CloseIfValid(HANDLE handle)
1637 if (handle != INVALID_HANDLE_VALUE)
1638 CloseHandle(handle);
1642 open_bpipe(char *prog, int wait, const char *mode)
1644 HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
1645 hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup,
1648 SECURITY_ATTRIBUTES saAttr;
1652 hChildStdinRd = hChildStdinWr = hChildStdinWrDup =
1653 hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup =
1654 hInputFile = INVALID_HANDLE_VALUE;
1656 BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
1657 memset((void *)bpipe, 0, sizeof(BPIPE));
1659 int mode_read = (mode[0] == 'r');
1660 int mode_write = (mode[0] == 'w' || mode[1] == 'w');
1663 // Set the bInheritHandle flag so pipe handles are inherited.
1665 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1666 saAttr.bInheritHandle = TRUE;
1667 saAttr.lpSecurityDescriptor = NULL;
1671 // Create a pipe for the child process's STDOUT.
1672 if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
1673 ErrorExit("Stdout pipe creation failed\n");
1676 // Create noninheritable read handle and close the inheritable read
1679 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
1680 GetCurrentProcess(), &hChildStdoutRdDup , 0,
1682 DUPLICATE_SAME_ACCESS);
1684 ErrorExit("DuplicateHandle failed");
1688 CloseHandle(hChildStdoutRd);
1689 hChildStdoutRd = INVALID_HANDLE_VALUE;
1694 // Create a pipe for the child process's STDIN.
1696 if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
1697 ErrorExit("Stdin pipe creation failed\n");
1701 // Duplicate the write handle to the pipe so it is not inherited.
1702 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
1703 GetCurrentProcess(), &hChildStdinWrDup,
1705 FALSE, // not inherited
1706 DUPLICATE_SAME_ACCESS);
1708 ErrorExit("DuplicateHandle failed");
1712 CloseHandle(hChildStdinWr);
1713 hChildStdinWr = INVALID_HANDLE_VALUE;
1715 // spawn program with redirected handles as appropriate
1716 bpipe->worker_pid = (pid_t)
1717 CreateChildProcess(prog, // commandline
1718 hChildStdinRd, // stdin HANDLE
1719 hChildStdoutWr, // stdout HANDLE
1720 hChildStdoutWr); // stderr HANDLE
1722 if ((HANDLE) bpipe->worker_pid == INVALID_HANDLE_VALUE)
1726 bpipe->worker_stime = time(NULL);
1729 CloseHandle(hChildStdoutWr); // close our write side so when
1730 // process terminates we can
1732 // ugly but convert WIN32 HANDLE to FILE*
1733 int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
1735 bpipe->rfd = _fdopen(rfd, "r");
1739 CloseHandle(hChildStdinRd); // close our read side so as not
1740 // to interfre with child's copy
1741 // ugly but convert WIN32 HANDLE to FILE*
1742 int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
1744 bpipe->wfd = _fdopen(wfd, "w");
1749 bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
1756 CloseIfValid(hChildStdoutRd);
1757 CloseIfValid(hChildStdoutRdDup);
1758 CloseIfValid(hChildStdinWr);
1759 CloseIfValid(hChildStdinWrDup);
1761 free((void *) bpipe);
1762 errno = b_errno_win32; /* do GetLastError() for error code */
1768 kill(int pid, int signal)
1771 if (!TerminateProcess((HANDLE)pid, (UINT) signal)) {
1773 errno = b_errno_win32;
1775 CloseHandle((HANDLE)pid);
1781 close_bpipe(BPIPE *bpipe)
1784 int32_t remaining_wait = bpipe->wait;
1786 if (remaining_wait == 0) { /* wait indefinitely */
1787 remaining_wait = INT32_MAX;
1791 if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode)) {
1792 const char *err = errorString();
1793 rval = b_errno_win32;
1794 d_msg(__FILE__, __LINE__, 0,
1795 "GetExitCode error %s\n", err);
1796 LocalFree((void *)err);
1799 if (exitCode == STILL_ACTIVE) {
1800 if (remaining_wait <= 0) {
1801 rval = ETIME; /* timed out */
1804 bmicrosleep(1, 0); /* wait one second */
1806 } else if (exitCode != 0) {
1807 /* Truncate exit code as it doesn't seem to be correct */
1808 rval = (exitCode & 0xFF) | b_errno_exit;
1811 break; /* Shouldn't get here */
1815 if (bpipe->timer_id) {
1816 stop_child_timer(bpipe->timer_id);
1818 if (bpipe->rfd) fclose(bpipe->rfd);
1819 if (bpipe->wfd) fclose(bpipe->wfd);
1820 free((void *)bpipe);
1825 close_wpipe(BPIPE *bpipe)
1831 if (fclose(bpipe->wfd) != 0) {
1839 #include "findlib/find.h"
1842 utime(const char *fname, struct utimbuf *times)
1847 conv_unix_to_win32_path(fname, tmpbuf, 5000);
1849 cvt_utime_to_ftime(times->actime, acc);
1850 cvt_utime_to_ftime(times->modtime, mod);
1852 HANDLE h = INVALID_HANDLE_VALUE;
1854 if (p_CreateFileW) {
1855 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1856 make_win32_path_UTF8_2_wchar(&pwszBuf, tmpbuf);
1858 h = p_CreateFileW((LPCWSTR)pwszBuf,
1859 FILE_WRITE_ATTRIBUTES,
1860 FILE_SHARE_WRITE|FILE_SHARE_READ|FILE_SHARE_DELETE,
1863 FILE_FLAG_BACKUP_SEMANTICS, // required for directories
1866 free_pool_memory(pwszBuf);
1867 } else if (p_CreateFileA) {
1868 h = p_CreateFileA(tmpbuf,
1869 FILE_WRITE_ATTRIBUTES,
1870 FILE_SHARE_WRITE|FILE_SHARE_READ|FILE_SHARE_DELETE,
1873 FILE_FLAG_BACKUP_SEMANTICS, // required for directories
1877 if (h == INVALID_HANDLE_VALUE) {
1878 const char *err = errorString();
1879 d_msg(__FILE__, __LINE__, 99,
1880 "Cannot open file \"%s\" for utime(): ERR=%s", tmpbuf, err);
1881 LocalFree((void *)err);
1882 errno = b_errno_win32;
1886 int rval = SetFileTime(h, NULL, &acc, &mod) ? 0 : -1;
1889 errno = b_errno_win32;
1896 file_open(const char *file, int flags, int mode)
1899 DWORD shareMode = 0;
1902 HANDLE foo = INVALID_HANDLE_VALUE;
1903 const char *remap = file;
1905 if (flags & O_WRONLY) access = GENERIC_WRITE;
1906 else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
1907 else access = GENERIC_READ;
1909 if ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
1910 create = CREATE_NEW;
1911 else if ((flags & (O_CREAT | O_TRUNC)) == (O_CREAT | O_TRUNC))
1912 create = CREATE_ALWAYS;
1913 else if (flags & O_CREAT)
1914 create = OPEN_ALWAYS;
1915 else if (flags & O_TRUNC)
1916 create = TRUNCATE_EXISTING;
1918 create = OPEN_EXISTING;
1922 if (flags & O_APPEND) {
1923 printf("open...APPEND not implemented yet.");
1927 if (p_CreateFileW) {
1928 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1929 make_win32_path_UTF8_2_wchar(&pwszBuf, file);
1931 foo = p_CreateFileW((LPCWSTR) pwszBuf, access, shareMode, NULL, create, msflags, NULL);
1932 free_pool_memory(pwszBuf);
1933 } else if (p_CreateFileA)
1934 foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
1936 if (INVALID_HANDLE_VALUE == foo) {
1937 errno = b_errno_win32;
1948 if (!CloseHandle((HANDLE)fd)) {
1949 errno = b_errno_win32;
1957 file_write(int fd, const void *data, ssize_t len)
1961 status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
1962 if (status) return bwrite;
1963 errno = b_errno_win32;
1969 file_read(int fd, void *data, ssize_t len)
1974 status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
1975 if (status) return bread;
1976 errno = b_errno_win32;
1981 file_seek(int fd, off_t offset, int whence)
1987 method = FILE_BEGIN;
1990 method = FILE_CURRENT;
2000 if ((val=SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method)) == INVALID_SET_FILE_POINTER) {
2001 errno = b_errno_win32;
2004 /* ***FIXME*** I doubt this works right */
2017 /* syslog function, added by Nicolas Boichat */
2018 void openlog(const char *ident, int option, int facility) {}