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
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
25 #define b_errno_win32 (1<<29)
29 #include "../../lib/winapi.h"
32 /* to allow the usage of the original version in this file here */
36 #define USE_WIN32_COMPAT_IO 1
38 extern void d_msg(const char *file, int line, int level, const char *fmt,...);
39 extern DWORD g_platform_id;
40 extern int enable_vss;
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
51 void conv_unix_to_win32_path(const char *name, char *win32_name, DWORD dwSize)
53 const char *fname = name;
54 char *tname = win32_name;
56 /* Check for Unix separator and convert to Win32 */
57 if (name[0] == '/' && name[1] == '/') { /* double slash? */
58 name++; /* yes, skip first one */
61 *win32_name++ = '\\'; /* convert char */
62 /* If Win32 separated that is "quoted", remove quote */
63 } else if (*name == '\\' && name[1] == '\\') {
65 name++; /* skip first \ */
67 *win32_name++ = *name; /* copy character */
71 /* Strip any trailing slash, if we stored something */
72 if (*fname != 0 && win32_name[-1] == '\\') {
79 /* here we convert to VSS specific file name which
80 can get longer because VSS will make something like
81 \\\\?\\GLOBALROOT\\Device\\HarddiskVolumeShadowCopy1\\bacula\\uninstall.exe
82 from c:\bacula\uninstall.exe
84 if (g_pVSSClient && enable_vss && g_pVSSClient->IsInitialized()) {
85 POOLMEM *pszBuf = get_pool_memory (PM_FNAME);
86 pszBuf = check_pool_memory_size(pszBuf, dwSize);
87 bstrncpy(pszBuf, tname, strlen(tname)+1);
88 g_pVSSClient->GetShadowPath(pszBuf, tname, dwSize);
89 free_pool_memory(pszBuf);
95 wchar_2_UTF8(char *pszUTF, const WCHAR *pszUCS, int cchChar)
97 /* the return value is the number of bytes written to the buffer.
98 The number includes the byte for the null terminator. */
100 if (p_WideCharToMultiByte) {
101 int nRet = p_WideCharToMultiByte(CP_UTF8,0,pszUCS,-1,pszUTF,cchChar,NULL,NULL);
110 UTF8_2_wchar(POOLMEM **ppszUCS, const char *pszUTF)
112 /* the return value is the number of wide characters written to the buffer. */
113 /* convert null terminated string from utf-8 to ucs2, enlarge buffer if necessary */
115 if (p_MultiByteToWideChar) {
116 /* strlen of UTF8 +1 is enough */
117 DWORD cchSize = (strlen(pszUTF)+1);
118 *ppszUCS = check_pool_memory_size(*ppszUCS, cchSize*sizeof (WCHAR));
120 int nRet = p_MultiByteToWideChar(CP_UTF8, 0, pszUTF, -1, (LPWSTR) *ppszUCS,cchSize);
130 wchar_win32_path(const char *name, WCHAR *win32_name)
132 const char *fname = name;
134 /* Check for Unix separator and convert to Win32 */
136 *win32_name++ = '\\'; /* convert char */
137 /* If Win32 separated that is "quoted", remove quote */
138 } else if (*name == '\\' && name[1] == '\\') {
139 *win32_name++ = '\\';
140 name++; /* skip first \ */
142 *win32_name++ = *name; /* copy character */
146 /* Strip any trailing slash, if we stored something */
147 if (*fname != 0 && win32_name[-1] == '\\') {
159 int chmod(const char *, mode_t)
164 int chown(const char *k, uid_t, gid_t)
169 int lchown(const char *k, uid_t, gid_t)
175 bool fstype(const char *fname, char *fs, int fslen)
177 return true; /* accept anything */
189 srandom(unsigned int seed)
193 // /////////////////////////////////////////////////////////////////
194 // convert from Windows concept of time to Unix concept of time
195 // /////////////////////////////////////////////////////////////////
197 cvt_utime_to_ftime(const time_t &time, FILETIME &wintime)
199 uint64_t mstime = time;
200 mstime *= WIN32_FILETIME_SCALE;
201 mstime += WIN32_FILETIME_ADJUST;
204 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffUL);
206 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffI64);
208 wintime.dwHighDateTime = (DWORD) ((mstime>>32)& 0xffffffffUL);
212 cvt_ftime_to_utime(const FILETIME &time)
214 uint64_t mstime = time.dwHighDateTime;
216 mstime |= time.dwLowDateTime;
218 mstime -= WIN32_FILETIME_ADJUST;
219 mstime /= WIN32_FILETIME_SCALE; // convert to seconds.
221 return (time_t) (mstime & 0xffffffff);
229 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
230 FORMAT_MESSAGE_FROM_SYSTEM |
231 FORMAT_MESSAGE_IGNORE_INSERTS,
234 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default lang
239 return (const char *) lpMsgBuf;
245 statDir(const char *file, struct stat *sb)
247 WIN32_FIND_DATAW info_w; // window's file info
248 WIN32_FIND_DATAA info_a; // window's file info
250 // cache some common vars to make code more transparent
251 DWORD* pdwFileAttributes;
252 DWORD* pnFileSizeHigh;
253 DWORD* pnFileSizeLow;
254 FILETIME* pftLastAccessTime;
255 FILETIME* pftLastWriteTime;
256 FILETIME* pftCreationTime;
258 if (file[1] == ':' && file[2] == 0) {
259 d_msg(__FILE__, __LINE__, 99, "faking ROOT attrs(%s).\n", file);
260 sb->st_mode = S_IFDIR;
261 sb->st_mode |= S_IREAD|S_IEXEC|S_IWRITE;
268 HANDLE h = INVALID_HANDLE_VALUE;
270 // use unicode or ascii
271 if (p_FindFirstFileW) {
272 POOLMEM* pwszBuf = get_pool_memory (PM_FNAME);
273 UTF8_2_wchar(&pwszBuf, file);
275 h = p_FindFirstFileW((LPCWSTR) pwszBuf, &info_w);
276 free_pool_memory(pwszBuf);
278 pdwFileAttributes = &info_w.dwFileAttributes;
279 pnFileSizeHigh = &info_w.nFileSizeHigh;
280 pnFileSizeLow = &info_w.nFileSizeLow;
281 pftLastAccessTime = &info_w.ftLastAccessTime;
282 pftLastWriteTime = &info_w.ftLastWriteTime;
283 pftCreationTime = &info_w.ftCreationTime;
285 else if (p_FindFirstFileA) {
286 h = p_FindFirstFileA(file, &info_a);
288 pdwFileAttributes = &info_a.dwFileAttributes;
289 pnFileSizeHigh = &info_a.nFileSizeHigh;
290 pnFileSizeLow = &info_a.nFileSizeLow;
291 pftLastAccessTime = &info_a.ftLastAccessTime;
292 pftLastWriteTime = &info_a.ftLastWriteTime;
293 pftCreationTime = &info_a.ftCreationTime;
296 if (h == INVALID_HANDLE_VALUE) {
297 const char *err = errorString();
298 d_msg(__FILE__, __LINE__, 99, "FindFirstFile(%s):%s\n", file, err);
299 LocalFree((void *)err);
300 errno = b_errno_win32;
304 sb->st_mode = 0777; /* start with everything */
305 if (*pdwFileAttributes & FILE_ATTRIBUTE_READONLY)
306 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
307 if (*pdwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
308 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
309 if (*pdwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
310 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
311 sb->st_mode |= S_IFDIR;
313 sb->st_size = *pnFileSizeHigh;
315 sb->st_size |= *pnFileSizeLow;
316 sb->st_blksize = 4096;
317 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
319 sb->st_atime = cvt_ftime_to_utime(*pftLastAccessTime);
320 sb->st_mtime = cvt_ftime_to_utime(*pftLastWriteTime);
321 sb->st_ctime = cvt_ftime_to_utime(*pftCreationTime);
328 stat2(const char *file, struct stat *sb)
330 BY_HANDLE_FILE_INFORMATION info;
334 conv_unix_to_win32_path(file, tmpbuf, 1024);
338 if (p_GetFileAttributesW) {
339 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
340 UTF8_2_wchar(&pwszBuf, tmpbuf);
342 attr = p_GetFileAttributesW((LPCWSTR) pwszBuf);
343 free_pool_memory(pwszBuf);
344 } else if (p_GetFileAttributesA) {
345 attr = p_GetFileAttributesA(tmpbuf);
349 const char *err = errorString();
350 d_msg(__FILE__, __LINE__, 99,
351 "GetFileAttrubtes(%s): %s\n", tmpbuf, err);
352 LocalFree((void *)err);
353 errno = b_errno_win32;
357 if (attr & FILE_ATTRIBUTE_DIRECTORY)
358 return statDir(tmpbuf, sb);
360 h = CreateFileA(tmpbuf, GENERIC_READ,
361 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
363 if (h == INVALID_HANDLE_VALUE) {
364 const char *err = errorString();
365 d_msg(__FILE__, __LINE__, 99,
366 "Cannot open file for stat (%s):%s\n", tmpbuf, err);
367 LocalFree((void *)err);
369 errno = b_errno_win32;
373 if (!GetFileInformationByHandle(h, &info)) {
374 const char *err = errorString();
375 d_msg(__FILE__, __LINE__, 99,
376 "GetfileInformationByHandle(%s): %s\n", tmpbuf, err);
377 LocalFree((void *)err);
379 errno = b_errno_win32;
383 sb->st_dev = info.dwVolumeSerialNumber;
384 sb->st_ino = info.nFileIndexHigh;
386 sb->st_ino |= info.nFileIndexLow;
387 sb->st_nlink = (short)info.nNumberOfLinks;
388 if (sb->st_nlink > 1) {
389 d_msg(__FILE__, __LINE__, 99, "st_nlink=%d\n", sb->st_nlink);
392 sb->st_mode = 0777; /* start with everything */
393 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
394 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
395 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
396 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
397 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
398 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
399 sb->st_mode |= S_IFREG;
401 sb->st_size = info.nFileSizeHigh;
403 sb->st_size |= info.nFileSizeLow;
404 sb->st_blksize = 4096;
405 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
406 sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
407 sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
408 sb->st_ctime = cvt_ftime_to_utime(info.ftCreationTime);
416 stat(const char *file, struct stat *sb)
418 WIN32_FILE_ATTRIBUTE_DATA data;
422 memset(sb, 0, sizeof(*sb));
424 if (g_platform_id == VER_PLATFORM_WIN32_WINDOWS) {
425 return stat2(file, sb);
428 // otherwise we're on NT
436 wchar_win32_path(file, buf+4);
438 if (!GetFileAttributesExW((WCHAR *)buf, GetFileExInfoStandard, &data)) {
439 return stat2(file, sb);
443 if (p_GetFileAttributesExW) {
444 /* dynamically allocate enough space for UCS2 filename */
445 POOLMEM* pwszBuf = get_pool_memory (PM_FNAME);
446 UTF8_2_wchar(&pwszBuf, file);
448 BOOL b = p_GetFileAttributesExW((LPCWSTR) pwszBuf, GetFileExInfoStandard, &data);
449 free_pool_memory(pwszBuf);
452 return stat2(file, sb);
454 } else if (p_GetFileAttributesExA) {
455 if (!p_GetFileAttributesExA(file, GetFileExInfoStandard, &data)) {
456 return stat2(file, sb);
459 return stat2(file, sb);
464 sb->st_mode = 0777; /* start with everything */
465 if (data.dwFileAttributes & FILE_ATTRIBUTE_READONLY) {
466 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
468 if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
469 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
471 if (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
472 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
474 if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
475 sb->st_mode |= S_IFDIR;
477 sb->st_mode |= S_IFREG;
481 sb->st_size = data.nFileSizeHigh;
483 sb->st_size |= data.nFileSizeLow;
484 sb->st_blksize = 4096;
485 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
486 sb->st_atime = cvt_ftime_to_utime(data.ftLastAccessTime);
487 sb->st_mtime = cvt_ftime_to_utime(data.ftLastWriteTime);
488 sb->st_ctime = cvt_ftime_to_utime(data.ftCreationTime);
495 lstat(const char *file, struct stat *sb)
497 return stat(file, sb);
513 execvp(const char *, char *[]) {
534 waitpid(int, int*, int)
541 readlink(const char *, char *, int)
550 strcasecmp(const char *s1, const char *s2)
552 register int ch1, ch2;
555 return 0; /* strings are equal if same object. */
565 } while (ch1 != 0 && tolower(ch1) == tolower(ch2));
572 strncasecmp(const char *s1, const char *s2, int len)
574 register int ch1, ch2;
577 return 0; /* strings are equal if same object. */
587 if (ch1 == 0 || tolower(ch1) != tolower(ch2)) break;
594 gettimeofday(struct timeval *tv, struct timezone *)
604 if (!SystemTimeToFileTime(&now, &tmp)) {
605 errno = b_errno_win32;
609 int64_t _100nsec = tmp.dwHighDateTime;
611 _100nsec |= tmp.dwLowDateTime;
612 _100nsec -= WIN32_FILETIME_ADJUST;
614 tv->tv_sec =(long) (_100nsec / 10000000);
615 tv->tv_usec = (long) ((_100nsec % 10000000)/10);
621 syslog(int type, const char *fmt, const char *msg)
623 /*#ifndef HAVE_CONSOLE
624 MessageBox(NULL, msg, "Bacula", MB_OK);
641 // implement opendir/readdir/closedir on top of window's API
645 WIN32_FIND_DATAA data_a; // window's file info (ansii version)
646 WIN32_FIND_DATAW data_w; // window's file info (wchar version)
647 const char *spec; // the directory we're traversing
648 HANDLE dirh; // the search handle
649 BOOL valid_a; // the info in data_a field is valid
650 BOOL valid_w; // the info in data_w field is valid
651 UINT32 offset; // pseudo offset for d_off
655 opendir(const char *path)
657 /* enough space for VSS !*/
658 int max_len = strlen(path) + MAX_PATH;
665 rval = (_dir *)malloc(sizeof(_dir));
666 memset (rval, 0, sizeof (_dir));
667 if (rval == NULL) return NULL;
668 char *tspec = (char *)malloc(max_len);
669 if (tspec == NULL) return NULL;
671 if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS) {
673 /* will append \\?\ at front itself */
674 conv_unix_to_win32_path(path, tspec, max_len-4);
676 /* allow path to be 32767 bytes */
682 conv_unix_to_win32_path(path, tspec+4, max_len-4);
685 conv_unix_to_win32_path(path, tspec, max_len);
688 bstrncat(tspec, "\\*", max_len);
692 if (p_FindFirstFileW) {
693 POOLMEM* pwcBuf = get_pool_memory(PM_FNAME);;
694 UTF8_2_wchar(&pwcBuf,rval->spec);
695 rval->dirh = p_FindFirstFileW((LPCWSTR)pwcBuf, &rval->data_w);
697 free_pool_memory(pwcBuf);
699 if (rval->dirh != INVALID_HANDLE_VALUE)
701 } else if (p_FindFirstFileA) {
702 rval->dirh = p_FindFirstFileA(rval->spec, &rval->data_a);
704 if (rval->dirh != INVALID_HANDLE_VALUE)
709 d_msg(__FILE__, __LINE__,
710 99, "opendir(%s)\n\tspec=%s,\n\tFindFirstFile returns %d\n",
711 path, rval->spec, rval->dirh);
714 if (rval->dirh == INVALID_HANDLE_VALUE)
718 d_msg(__FILE__, __LINE__,
719 99, "\tFirstFile=%s\n", rval->data_w.cFileName);
722 d_msg(__FILE__, __LINE__,
723 99, "\tFirstFile=%s\n", rval->data_a.cFileName);
728 free((void *)rval->spec);
730 errno = b_errno_win32;
737 _dir *dp = (_dir *)dirp;
739 free((void *)dp->spec);
745 typedef struct _WIN32_FIND_DATA {
746 DWORD dwFileAttributes;
747 FILETIME ftCreationTime;
748 FILETIME ftLastAccessTime;
749 FILETIME ftLastWriteTime;
754 TCHAR cFileName[MAX_PATH];
755 TCHAR cAlternateFileName[14];
756 } WIN32_FIND_DATA, *PWIN32_FIND_DATA;
760 copyin(struct dirent &dp, const char *fname)
764 char *cp = dp.d_name;
774 readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
776 _dir *dp = (_dir *)dirp;
777 if (dp->valid_w || dp->valid_a) {
778 entry->d_off = dp->offset;
782 char szBuf[MAX_PATH_UTF8];
783 wchar_2_UTF8(szBuf,dp->data_w.cFileName);
784 dp->offset += copyin(*entry, szBuf);
785 } else if (dp->valid_a) { // copy ansi (only 1 will be valid)
786 dp->offset += copyin(*entry, dp->data_a.cFileName);
789 *result = entry; /* return entry address */
790 d_msg(__FILE__, __LINE__,
791 99, "readdir_r(%p, { d_name=\"%s\", d_reclen=%d, d_off=%d\n",
792 dirp, entry->d_name, entry->d_reclen, entry->d_off);
794 // d_msg(__FILE__, __LINE__, 99, "readdir_r !valid\n");
795 errno = b_errno_win32;
799 // get next file, try unicode first
801 dp->valid_w = p_FindNextFileW(dp->dirh, &dp->data_w);
802 else if (p_FindNextFileA)
803 dp->valid_a = p_FindNextFileA(dp->dirh, &dp->data_a);
813 * Dotted IP address to network address
819 inet_aton(const char *a, struct in_addr *inp)
822 uint32_t acc = 0, tmp = 0;
825 if (!isdigit(*cp)) { /* first char must be digit */
826 return 0; /* error */
830 tmp = (tmp * 10) + (*cp -'0');
831 } else if (*cp == '.' || *cp == 0) {
833 return 0; /* error */
835 acc = (acc << 8) + tmp;
839 return 0; /* error */
841 } while (*cp++ != 0);
842 if (dotc != 4) { /* want 3 .'s plus EOS */
843 return 0; /* error */
845 inp->s_addr = htonl(acc); /* store addr in network format */
850 nanosleep(const struct timespec *req, struct timespec *rem)
853 rem->tv_sec = rem->tv_nsec = 0;
854 Sleep((req->tv_sec * 1000) + (req->tv_nsec/100000));
859 init_signals(void terminate(int sig))
865 init_stack_dump(void)
872 pathconf(const char *path, int name)
876 if (strncmp(path, "\\\\?\\", 4) == 0)
888 WORD wVersionRequested = MAKEWORD( 1, 1);
891 int err = WSAStartup(wVersionRequested, &wsaData);
895 printf("Can not start Windows Sockets\n");
905 win32_chdir(const char *dir)
907 if (p_SetCurrentDirectoryW) {
908 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
909 UTF8_2_wchar(&pwszBuf, dir);
911 BOOL b=p_SetCurrentDirectoryW((LPCWSTR)pwszBuf);
912 free_pool_memory(pwszBuf);
915 errno = b_errno_win32;
919 else if (p_SetCurrentDirectoryA) {
920 if (0 == p_SetCurrentDirectoryA(dir)) {
921 errno = b_errno_win32;
931 win32_mkdir(const char *dir)
934 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
935 UTF8_2_wchar(&pwszBuf, dir);
937 int n=p_wmkdir((LPCWSTR)pwszBuf);
938 free_pool_memory(pwszBuf);
947 win32_getcwd(char *buf, int maxlen)
951 if (p_GetCurrentDirectoryW) {
952 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
953 pwszBuf = check_pool_memory_size (pwszBuf, maxlen*sizeof(WCHAR));
955 n = p_GetCurrentDirectoryW(maxlen, (LPWSTR) pwszBuf);
956 n = wchar_2_UTF8 (buf, (WCHAR*)pwszBuf, maxlen)-1;
957 free_pool_memory(pwszBuf);
959 } else if (p_GetCurrentDirectoryA)
960 n = p_GetCurrentDirectoryA(maxlen, buf);
962 if (n == 0 || n > maxlen) return NULL;
964 if (n+1 > maxlen) return NULL;
973 win32_fputs(const char *string, FILE *stream)
975 /* we use WriteConsoleA / WriteConsoleA
976 so we can be sure that unicode support works on win32.
977 with fallback if something fails
980 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
981 if (hOut && (hOut != INVALID_HANDLE_VALUE) && p_WideCharToMultiByte &&
982 p_MultiByteToWideChar && (stream == stdout)) {
984 POOLMEM* pwszBuf = get_pool_memory(PM_MESSAGE);
986 DWORD dwCharsWritten;
989 dwChars = UTF8_2_wchar(&pwszBuf, string);
991 /* try WriteConsoleW */
992 if (WriteConsoleW (hOut, pwszBuf, dwChars-1, &dwCharsWritten, NULL)) {
993 free_pool_memory(pwszBuf);
994 return dwCharsWritten;
997 /* convert to local codepage and try WriteConsoleA */
998 POOLMEM* pszBuf = get_pool_memory(PM_MESSAGE);
999 pszBuf = check_pool_memory_size(pszBuf, dwChars+1);
1001 dwChars = p_WideCharToMultiByte(GetConsoleOutputCP(),0,(LPCWSTR) pwszBuf,-1,pszBuf,dwChars,NULL,NULL);
1002 free_pool_memory(pwszBuf);
1004 if (WriteConsoleA (hOut, pszBuf, dwChars-1, &dwCharsWritten, NULL)) {
1005 free_pool_memory(pszBuf);
1006 return dwCharsWritten;
1010 return fputs(string, stream);
1014 win32_cgets (char* buffer, int len)
1016 /* we use console ReadConsoleA / ReadConsoleW to be able to read unicode
1017 from the win32 console and fallback if seomething fails */
1019 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
1020 if (hIn && (hIn != INVALID_HANDLE_VALUE) && p_WideCharToMultiByte && p_MultiByteToWideChar) {
1025 /* nt and unicode conversion */
1026 if (ReadConsoleW (hIn, wszBuf, 1024, &dwRead, NULL)) {
1028 /* null terminate at end */
1029 if (wszBuf[dwRead-1] == L'\n') {
1030 wszBuf[dwRead-1] = L'\0';
1034 if (wszBuf[dwRead-1] == L'\r') {
1035 wszBuf[dwRead-1] = L'\0';
1039 wchar_2_UTF8(buffer, wszBuf, len);
1043 /* win 9x and unicode conversion */
1044 if (ReadConsoleA (hIn, szBuf, 1024, &dwRead, NULL)) {
1046 /* null terminate at end */
1047 if (szBuf[dwRead-1] == L'\n') {
1048 szBuf[dwRead-1] = L'\0';
1052 if (szBuf[dwRead-1] == L'\r') {
1053 szBuf[dwRead-1] = L'\0';
1057 /* convert from ansii to WCHAR */
1058 p_MultiByteToWideChar(GetConsoleCP(), 0, szBuf, -1, wszBuf,1024);
1059 /* convert from WCHAR to UTF-8 */
1060 if (wchar_2_UTF8(buffer, wszBuf, len))
1066 if (fgets(buffer, len, stdin))
1073 win32_unlink(const char *filename)
1077 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1078 UTF8_2_wchar(&pwszBuf, filename);
1079 nRetCode = _wunlink((LPCWSTR) pwszBuf);
1081 /* special case if file is readonly,
1082 we retry but unset attribute before */
1083 if (nRetCode == -1 && errno == EACCES && p_SetFileAttributesW && p_GetFileAttributesW) {
1084 DWORD dwAttr = p_GetFileAttributesW((LPCWSTR)pwszBuf);
1085 if (dwAttr != INVALID_FILE_ATTRIBUTES) {
1086 if (p_SetFileAttributesW((LPCWSTR)pwszBuf, dwAttr & ~FILE_ATTRIBUTE_READONLY)) {
1087 nRetCode = _wunlink((LPCWSTR) pwszBuf);
1088 /* reset to original if it didn't help */
1090 p_SetFileAttributesW((LPCWSTR)pwszBuf, dwAttr);
1094 free_pool_memory(pwszBuf);
1096 nRetCode = _unlink(filename);
1098 /* special case if file is readonly,
1099 we retry but unset attribute before */
1100 if (nRetCode == -1 && errno == EACCES && p_SetFileAttributesA && p_GetFileAttributesA) {
1101 DWORD dwAttr = p_GetFileAttributesA(filename);
1102 if (dwAttr != INVALID_FILE_ATTRIBUTES) {
1103 if (p_SetFileAttributesA(filename, dwAttr & ~FILE_ATTRIBUTE_READONLY)) {
1104 nRetCode = _unlink(filename);
1105 /* reset to original if it didn't help */
1107 p_SetFileAttributesA(filename, dwAttr);
1116 #include "mswinver.h"
1118 char WIN_VERSION_LONG[64];
1119 char WIN_VERSION[32];
1126 static winver INIT; // cause constructor to be called before main()
1131 winver::winver(void)
1133 const char *version = "";
1134 const char *platform = "";
1135 OSVERSIONINFO osvinfo;
1136 osvinfo.dwOSVersionInfoSize = sizeof(osvinfo);
1138 // Get the current OS version
1139 if (!GetVersionEx(&osvinfo)) {
1140 version = "Unknown";
1141 platform = "Unknown";
1144 switch (_mkversion(osvinfo.dwPlatformId, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion))
1146 case MS_WINDOWS_95: (version = "Windows 95"); break;
1147 case MS_WINDOWS_98: (version = "Windows 98"); break;
1148 case MS_WINDOWS_ME: (version = "Windows ME"); break;
1149 case MS_WINDOWS_NT4:(version = "Windows NT 4.0"); platform = "NT"; break;
1150 case MS_WINDOWS_2K: (version = "Windows 2000");platform = "NT"; break;
1151 case MS_WINDOWS_XP: (version = "Windows XP");platform = "NT"; break;
1152 case MS_WINDOWS_S2003: (version = "Windows Server 2003");platform = "NT"; break;
1153 default: version = "Windows ??"; break;
1156 bstrncpy(WIN_VERSION_LONG, version, sizeof(WIN_VERSION_LONG));
1157 snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %d.%d.%d",
1158 platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
1161 HANDLE h = CreateFile("G:\\foobar", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
1165 BPIPE *b = open_bpipe("ls -l", 10, "r");
1167 while (!feof(b->rfd)) {
1168 fgets(buf, sizeof(buf), b->rfd);
1174 BOOL CreateChildProcess(VOID);
1175 VOID WriteToPipe(VOID);
1176 VOID ReadFromPipe(VOID);
1177 VOID ErrorExit(LPCSTR);
1178 VOID ErrMsg(LPTSTR, BOOL);
1181 * Check for a quoted path, if an absolute path name is given and it contains
1182 * spaces it will need to be quoted. i.e. "c:/Program Files/foo/bar.exe"
1183 * CreateProcess() says the best way to ensure proper results with executables
1184 * with spaces in path or filename is to quote the string.
1187 getArgv0(const char *cmdline)
1191 for (const char *cp = cmdline; *cp; cp++)
1196 if (!inquote && isspace(*cp))
1201 int len = cp - cmdline;
1202 char *rval = (char *)malloc(len+1);
1216 * OK, so it would seem CreateProcess only handles true executables:
1217 * .com or .exe files.
1218 * So test to see whether we're getting a .bat file and if so grab
1219 * $COMSPEC value and pass batch file to it.
1222 CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err)
1224 PROCESS_INFORMATION piProcInfo;
1225 STARTUPINFOA siStartInfo;
1226 BOOL bFuncRetn = FALSE;
1228 // Set up members of the PROCESS_INFORMATION structure.
1230 ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
1232 // Set up members of the STARTUPINFO structure.
1234 ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
1235 siStartInfo.cb = sizeof(STARTUPINFO);
1236 // setup new process to use supplied handles for stdin,stdout,stderr
1237 // if supplied handles are not used the send a copy of our STD_HANDLE
1239 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
1241 if (in != INVALID_HANDLE_VALUE)
1242 siStartInfo.hStdInput = in;
1244 siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1246 if (out != INVALID_HANDLE_VALUE)
1247 siStartInfo.hStdOutput = out;
1249 siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1250 if (err != INVALID_HANDLE_VALUE)
1251 siStartInfo.hStdError = err;
1253 siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1254 // Create the child process.
1258 const char *comspec = getenv("COMSPEC");
1260 if (comspec == NULL) // should never happen
1261 return INVALID_HANDLE_VALUE;
1263 char *cmdLine = (char *)alloca(strlen(cmdline) + strlen(comspec) + 16);
1265 strcpy(exeFile, comspec);
1266 strcpy(cmdLine, comspec);
1267 strcat(cmdLine, " /c ");
1268 strcat(cmdLine, cmdline);
1270 // try to execute program
1271 bFuncRetn = CreateProcessA(exeFile,
1272 cmdLine, // command line
1273 NULL, // process security attributes
1274 NULL, // primary thread security attributes
1275 TRUE, // handles are inherited
1276 0, // creation flags
1277 NULL, // use parent's environment
1278 NULL, // use parent's current directory
1279 &siStartInfo, // STARTUPINFO pointer
1280 &piProcInfo); // receives PROCESS_INFORMATION
1282 if (bFuncRetn == 0) {
1283 ErrorExit("CreateProcess failed\n");
1284 const char *err = errorString();
1285 d_msg(__FILE__, __LINE__, 99,
1286 "CreateProcess(%s, %s, ...)=%s\n", exeFile, cmdLine, err);
1287 LocalFree((void *)err);
1288 return INVALID_HANDLE_VALUE;
1290 // we don't need a handle on the process primary thread so we close
1292 CloseHandle(piProcInfo.hThread);
1294 return piProcInfo.hProcess;
1299 ErrorExit (LPCSTR lpszMessage)
1301 d_msg(__FILE__, __LINE__, 0, "%s", lpszMessage);
1306 typedef struct s_bpipe {
1308 time_t worker_stime;
1317 CloseIfValid(HANDLE handle)
1319 if (handle != INVALID_HANDLE_VALUE)
1320 CloseHandle(handle);
1325 open_bpipe(char *prog, int wait, const char *mode)
1327 HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
1328 hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup,
1331 SECURITY_ATTRIBUTES saAttr;
1335 hChildStdinRd = hChildStdinWr = hChildStdinWrDup =
1336 hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup =
1337 hInputFile = INVALID_HANDLE_VALUE;
1339 BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
1340 memset((void *)bpipe, 0, sizeof(BPIPE));
1342 int mode_read = (mode[0] == 'r');
1343 int mode_write = (mode[0] == 'w' || mode[1] == 'w');
1346 // Set the bInheritHandle flag so pipe handles are inherited.
1348 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1349 saAttr.bInheritHandle = TRUE;
1350 saAttr.lpSecurityDescriptor = NULL;
1354 // Create a pipe for the child process's STDOUT.
1355 if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
1356 ErrorExit("Stdout pipe creation failed\n");
1359 // Create noninheritable read handle and close the inheritable read
1362 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
1363 GetCurrentProcess(), &hChildStdoutRdDup , 0,
1365 DUPLICATE_SAME_ACCESS);
1367 ErrorExit("DuplicateHandle failed");
1371 CloseHandle(hChildStdoutRd);
1372 hChildStdoutRd = INVALID_HANDLE_VALUE;
1377 // Create a pipe for the child process's STDIN.
1379 if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
1380 ErrorExit("Stdin pipe creation failed\n");
1384 // Duplicate the write handle to the pipe so it is not inherited.
1385 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
1386 GetCurrentProcess(), &hChildStdinWrDup,
1388 FALSE, // not inherited
1389 DUPLICATE_SAME_ACCESS);
1391 ErrorExit("DuplicateHandle failed");
1395 CloseHandle(hChildStdinWr);
1396 hChildStdinWr = INVALID_HANDLE_VALUE;
1398 // spawn program with redirected handles as appropriate
1399 bpipe->worker_pid = (pid_t)
1400 CreateChildProcess(prog, // commandline
1401 hChildStdinRd, // stdin HANDLE
1402 hChildStdoutWr, // stdout HANDLE
1403 hChildStdoutWr); // stderr HANDLE
1405 if ((HANDLE) bpipe->worker_pid == INVALID_HANDLE_VALUE)
1409 bpipe->worker_stime = time(NULL);
1412 CloseHandle(hChildStdoutWr); // close our write side so when
1413 // process terminates we can
1415 // ugly but convert WIN32 HANDLE to FILE*
1416 int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
1418 bpipe->rfd = _fdopen(rfd, "r");
1422 CloseHandle(hChildStdinRd); // close our read side so as not
1423 // to interfre with child's copy
1424 // ugly but convert WIN32 HANDLE to FILE*
1425 int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
1427 bpipe->wfd = _fdopen(wfd, "w");
1432 bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
1439 CloseIfValid(hChildStdoutRd);
1440 CloseIfValid(hChildStdoutRdDup);
1441 CloseIfValid(hChildStdinWr);
1442 CloseIfValid(hChildStdinWrDup);
1444 free((void *) bpipe);
1445 errno = b_errno_win32; /* do GetLastError() for error code */
1452 kill(int pid, int signal)
1455 if (!TerminateProcess((HANDLE)pid, (UINT) signal)) {
1457 errno = b_errno_win32;
1459 CloseHandle((HANDLE)pid);
1466 close_bpipe(BPIPE *bpipe)
1469 int32_t remaining_wait = bpipe->wait;
1471 if (remaining_wait == 0) { /* wait indefinitely */
1472 remaining_wait = INT32_MAX;
1476 if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode)) {
1477 const char *err = errorString();
1478 rval = b_errno_win32;
1479 d_msg(__FILE__, __LINE__, 0,
1480 "GetExitCode error %s\n", err);
1481 LocalFree((void *)err);
1484 if (exitCode == STILL_ACTIVE) {
1485 if (remaining_wait <= 0) {
1486 rval = ETIME; /* timed out */
1489 bmicrosleep(1, 0); /* wait one second */
1491 } else if (exitCode != 0) {
1492 /* Truncate exit code as it doesn't seem to be correct */
1493 rval = (exitCode & 0xFF) | b_errno_exit;
1496 break; /* Shouldn't get here */
1500 if (bpipe->timer_id) {
1501 stop_child_timer(bpipe->timer_id);
1503 if (bpipe->rfd) fclose(bpipe->rfd);
1504 if (bpipe->wfd) fclose(bpipe->wfd);
1505 free((void *)bpipe);
1510 close_wpipe(BPIPE *bpipe)
1516 if (fclose(bpipe->wfd) != 0) {
1524 #include "findlib/find.h"
1527 utime(const char *fname, struct utimbuf *times)
1532 conv_unix_to_win32_path(fname, tmpbuf, 1024);
1534 cvt_utime_to_ftime(times->actime, acc);
1535 cvt_utime_to_ftime(times->modtime, mod);
1537 HANDLE h = INVALID_HANDLE_VALUE;
1539 if (p_CreateFileW) {
1540 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1541 UTF8_2_wchar(&pwszBuf, tmpbuf);
1543 h = p_CreateFileW((LPCWSTR) pwszBuf,
1544 FILE_WRITE_ATTRIBUTES,
1551 free_pool_memory(pwszBuf);
1552 } else if (p_CreateFileA) {
1553 h = p_CreateFileA(tmpbuf,
1554 FILE_WRITE_ATTRIBUTES,
1562 if (h == INVALID_HANDLE_VALUE) {
1563 const char *err = errorString();
1564 d_msg(__FILE__, __LINE__, 99,
1565 "Cannot open file \"%s\" for utime(): ERR=%s", tmpbuf, err);
1566 LocalFree((void *)err);
1567 errno = b_errno_win32;
1571 int rval = SetFileTime(h, NULL, &acc, &mod) ? 0 : -1;
1574 errno = b_errno_win32;
1579 #if USE_WIN32_COMPAT_IO
1582 open(const char *file, int flags, int mode)
1585 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1586 UTF8_2_wchar(&pwszBuf, file);
1588 int nRet = p_wopen((LPCWSTR) pwszBuf, flags|_O_BINARY, mode);
1589 free_pool_memory(pwszBuf);
1594 return _open(file, flags|_O_BINARY, mode);
1598 * Note, this works only for a file. If you want
1599 * to close a socket, use closesocket().
1600 * Bacula has been modified in src/lib/bnet.c
1601 * to use closesocket().
1609 #ifndef HAVE_WXCONSOLE
1611 read(int fd, void *buf, ssize_t len)
1613 return _read(fd, buf, (size_t)len);
1617 write(int fd, const void *buf, ssize_t len)
1619 return _write(fd, buf, (size_t)len);
1625 lseek(int fd, off_t offset, int whence)
1627 return _lseeki64(fd, offset, whence);
1631 dup2(int fd1, int fd2)
1633 return _dup2(fd1, fd2);
1637 open(const char *file, int flags, int mode)
1640 DWORD shareMode = 0;
1643 HANDLE foo = INVALID_HANDLE_VALUE;
1644 const char *remap = file;
1646 if (flags & O_WRONLY) access = GENERIC_WRITE;
1647 else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
1648 else access = GENERIC_READ;
1650 if (flags & O_CREAT) create = CREATE_NEW;
1651 else create = OPEN_EXISTING;
1653 if (flags & O_TRUNC) create = TRUNCATE_EXISTING;
1655 if (!(flags & O_EXCL))
1656 shareMode = FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE;
1658 if (flags & O_APPEND) {
1659 printf("open...APPEND not implemented yet.");
1663 if (p_CreateFileW) {
1664 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1665 UTF8_2_wchar(pwszBuf, file);
1667 foo = p_CreateFileW((LPCWSTR) pwszBuf, access, shareMode, NULL, create, msflags, NULL);
1668 free_pool_memory(pwszBuf);
1670 else if (p_CreateFileA)
1671 foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
1673 if (INVALID_HANDLE_VALUE == foo) {
1674 errno = b_errno_win32;
1685 if (!CloseHandle((HANDLE)fd)) {
1686 errno = b_errno_win32;
1694 write(int fd, const void *data, ssize_t len)
1698 status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
1699 if (status) return bwrite;
1700 errno = b_errno_win32;
1706 read(int fd, void *data, ssize_t len)
1711 status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
1712 if (status) return bread;
1713 errno = b_errno_win32;
1718 lseek(int fd, off_t offset, int whence)
1724 method = FILE_BEGIN;
1727 method = FILE_CURRENT;
1737 if ((val=SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method)) == INVALID_SET_FILE_POINTER) {
1738 errno = b_errno_win32;
1741 /* ***FIXME*** I doubt this works right */
1758 /* syslog function, added by Nicolas Boichat */