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);
1080 free_pool_memory(pwszBuf);
1082 nRetCode = _unlink(filename);
1088 #include "mswinver.h"
1090 char WIN_VERSION_LONG[64];
1091 char WIN_VERSION[32];
1098 static winver INIT; // cause constructor to be called before main()
1103 winver::winver(void)
1105 const char *version = "";
1106 const char *platform = "";
1107 OSVERSIONINFO osvinfo;
1108 osvinfo.dwOSVersionInfoSize = sizeof(osvinfo);
1110 // Get the current OS version
1111 if (!GetVersionEx(&osvinfo)) {
1112 version = "Unknown";
1113 platform = "Unknown";
1116 switch (_mkversion(osvinfo.dwPlatformId, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion))
1118 case MS_WINDOWS_95: (version = "Windows 95"); break;
1119 case MS_WINDOWS_98: (version = "Windows 98"); break;
1120 case MS_WINDOWS_ME: (version = "Windows ME"); break;
1121 case MS_WINDOWS_NT4:(version = "Windows NT 4.0"); platform = "NT"; break;
1122 case MS_WINDOWS_2K: (version = "Windows 2000");platform = "NT"; break;
1123 case MS_WINDOWS_XP: (version = "Windows XP");platform = "NT"; break;
1124 case MS_WINDOWS_S2003: (version = "Windows Server 2003");platform = "NT"; break;
1125 default: version = "Windows ??"; break;
1128 bstrncpy(WIN_VERSION_LONG, version, sizeof(WIN_VERSION_LONG));
1129 snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %d.%d.%d",
1130 platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
1133 HANDLE h = CreateFile("G:\\foobar", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
1137 BPIPE *b = open_bpipe("ls -l", 10, "r");
1139 while (!feof(b->rfd)) {
1140 fgets(buf, sizeof(buf), b->rfd);
1146 BOOL CreateChildProcess(VOID);
1147 VOID WriteToPipe(VOID);
1148 VOID ReadFromPipe(VOID);
1149 VOID ErrorExit(LPCSTR);
1150 VOID ErrMsg(LPTSTR, BOOL);
1153 * Check for a quoted path, if an absolute path name is given and it contains
1154 * spaces it will need to be quoted. i.e. "c:/Program Files/foo/bar.exe"
1155 * CreateProcess() says the best way to ensure proper results with executables
1156 * with spaces in path or filename is to quote the string.
1159 getArgv0(const char *cmdline)
1163 for (const char *cp = cmdline; *cp; cp++)
1168 if (!inquote && isspace(*cp))
1173 int len = cp - cmdline;
1174 char *rval = (char *)malloc(len+1);
1188 * OK, so it would seem CreateProcess only handles true executables:
1189 * .com or .exe files.
1190 * So test to see whether we're getting a .bat file and if so grab
1191 * $COMSPEC value and pass batch file to it.
1194 CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err)
1196 PROCESS_INFORMATION piProcInfo;
1197 STARTUPINFOA siStartInfo;
1198 BOOL bFuncRetn = FALSE;
1200 // Set up members of the PROCESS_INFORMATION structure.
1202 ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
1204 // Set up members of the STARTUPINFO structure.
1206 ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
1207 siStartInfo.cb = sizeof(STARTUPINFO);
1208 // setup new process to use supplied handles for stdin,stdout,stderr
1209 // if supplied handles are not used the send a copy of our STD_HANDLE
1211 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
1213 if (in != INVALID_HANDLE_VALUE)
1214 siStartInfo.hStdInput = in;
1216 siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1218 if (out != INVALID_HANDLE_VALUE)
1219 siStartInfo.hStdOutput = out;
1221 siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1222 if (err != INVALID_HANDLE_VALUE)
1223 siStartInfo.hStdError = err;
1225 siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1226 // Create the child process.
1230 const char *comspec = getenv("COMSPEC");
1232 if (comspec == NULL) // should never happen
1233 return INVALID_HANDLE_VALUE;
1235 char *cmdLine = (char *)alloca(strlen(cmdline) + strlen(comspec) + 16);
1237 strcpy(exeFile, comspec);
1238 strcpy(cmdLine, comspec);
1239 strcat(cmdLine, " /c ");
1240 strcat(cmdLine, cmdline);
1242 // try to execute program
1243 bFuncRetn = CreateProcessA(exeFile,
1244 cmdLine, // command line
1245 NULL, // process security attributes
1246 NULL, // primary thread security attributes
1247 TRUE, // handles are inherited
1248 0, // creation flags
1249 NULL, // use parent's environment
1250 NULL, // use parent's current directory
1251 &siStartInfo, // STARTUPINFO pointer
1252 &piProcInfo); // receives PROCESS_INFORMATION
1254 if (bFuncRetn == 0) {
1255 ErrorExit("CreateProcess failed\n");
1256 const char *err = errorString();
1257 d_msg(__FILE__, __LINE__, 99,
1258 "CreateProcess(%s, %s, ...)=%s\n", exeFile, cmdLine, err);
1259 LocalFree((void *)err);
1260 return INVALID_HANDLE_VALUE;
1262 // we don't need a handle on the process primary thread so we close
1264 CloseHandle(piProcInfo.hThread);
1266 return piProcInfo.hProcess;
1271 ErrorExit (LPCSTR lpszMessage)
1273 d_msg(__FILE__, __LINE__, 0, "%s", lpszMessage);
1278 typedef struct s_bpipe {
1280 time_t worker_stime;
1289 CloseIfValid(HANDLE handle)
1291 if (handle != INVALID_HANDLE_VALUE)
1292 CloseHandle(handle);
1297 open_bpipe(char *prog, int wait, const char *mode)
1299 HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
1300 hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup,
1303 SECURITY_ATTRIBUTES saAttr;
1307 hChildStdinRd = hChildStdinWr = hChildStdinWrDup =
1308 hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup =
1309 hInputFile = INVALID_HANDLE_VALUE;
1311 BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
1312 memset((void *)bpipe, 0, sizeof(BPIPE));
1314 int mode_read = (mode[0] == 'r');
1315 int mode_write = (mode[0] == 'w' || mode[1] == 'w');
1318 // Set the bInheritHandle flag so pipe handles are inherited.
1320 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1321 saAttr.bInheritHandle = TRUE;
1322 saAttr.lpSecurityDescriptor = NULL;
1326 // Create a pipe for the child process's STDOUT.
1327 if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
1328 ErrorExit("Stdout pipe creation failed\n");
1331 // Create noninheritable read handle and close the inheritable read
1334 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
1335 GetCurrentProcess(), &hChildStdoutRdDup , 0,
1337 DUPLICATE_SAME_ACCESS);
1339 ErrorExit("DuplicateHandle failed");
1343 CloseHandle(hChildStdoutRd);
1344 hChildStdoutRd = INVALID_HANDLE_VALUE;
1349 // Create a pipe for the child process's STDIN.
1351 if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
1352 ErrorExit("Stdin pipe creation failed\n");
1356 // Duplicate the write handle to the pipe so it is not inherited.
1357 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
1358 GetCurrentProcess(), &hChildStdinWrDup,
1360 FALSE, // not inherited
1361 DUPLICATE_SAME_ACCESS);
1363 ErrorExit("DuplicateHandle failed");
1367 CloseHandle(hChildStdinWr);
1368 hChildStdinWr = INVALID_HANDLE_VALUE;
1370 // spawn program with redirected handles as appropriate
1371 bpipe->worker_pid = (pid_t)
1372 CreateChildProcess(prog, // commandline
1373 hChildStdinRd, // stdin HANDLE
1374 hChildStdoutWr, // stdout HANDLE
1375 hChildStdoutWr); // stderr HANDLE
1377 if ((HANDLE) bpipe->worker_pid == INVALID_HANDLE_VALUE)
1381 bpipe->worker_stime = time(NULL);
1384 CloseHandle(hChildStdoutWr); // close our write side so when
1385 // process terminates we can
1387 // ugly but convert WIN32 HANDLE to FILE*
1388 int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
1390 bpipe->rfd = _fdopen(rfd, "r");
1394 CloseHandle(hChildStdinRd); // close our read side so as not
1395 // to interfre with child's copy
1396 // ugly but convert WIN32 HANDLE to FILE*
1397 int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
1399 bpipe->wfd = _fdopen(wfd, "w");
1404 bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
1411 CloseIfValid(hChildStdoutRd);
1412 CloseIfValid(hChildStdoutRdDup);
1413 CloseIfValid(hChildStdinWr);
1414 CloseIfValid(hChildStdinWrDup);
1416 free((void *) bpipe);
1417 errno = b_errno_win32; /* do GetLastError() for error code */
1424 kill(int pid, int signal)
1427 if (!TerminateProcess((HANDLE)pid, (UINT) signal)) {
1429 errno = b_errno_win32;
1431 CloseHandle((HANDLE)pid);
1438 close_bpipe(BPIPE *bpipe)
1441 int32_t remaining_wait = bpipe->wait;
1443 if (remaining_wait == 0) { /* wait indefinitely */
1444 remaining_wait = INT32_MAX;
1448 if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode)) {
1449 const char *err = errorString();
1450 rval = b_errno_win32;
1451 d_msg(__FILE__, __LINE__, 0,
1452 "GetExitCode error %s\n", err);
1453 LocalFree((void *)err);
1456 if (exitCode == STILL_ACTIVE) {
1457 if (remaining_wait <= 0) {
1458 rval = ETIME; /* timed out */
1461 bmicrosleep(1, 0); /* wait one second */
1463 } else if (exitCode != 0) {
1464 /* Truncate exit code as it doesn't seem to be correct */
1465 rval = (exitCode & 0xFF) | b_errno_exit;
1468 break; /* Shouldn't get here */
1472 if (bpipe->timer_id) {
1473 stop_child_timer(bpipe->timer_id);
1475 if (bpipe->rfd) fclose(bpipe->rfd);
1476 if (bpipe->wfd) fclose(bpipe->wfd);
1477 free((void *)bpipe);
1482 close_wpipe(BPIPE *bpipe)
1488 if (fclose(bpipe->wfd) != 0) {
1496 #include "findlib/find.h"
1499 utime(const char *fname, struct utimbuf *times)
1504 conv_unix_to_win32_path(fname, tmpbuf, 1024);
1506 cvt_utime_to_ftime(times->actime, acc);
1507 cvt_utime_to_ftime(times->modtime, mod);
1509 HANDLE h = INVALID_HANDLE_VALUE;
1511 if (p_CreateFileW) {
1512 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1513 UTF8_2_wchar(&pwszBuf, tmpbuf);
1515 h = p_CreateFileW((LPCWSTR) pwszBuf,
1516 FILE_WRITE_ATTRIBUTES,
1523 free_pool_memory(pwszBuf);
1524 } else if (p_CreateFileA) {
1525 h = p_CreateFileA(tmpbuf,
1526 FILE_WRITE_ATTRIBUTES,
1534 if (h == INVALID_HANDLE_VALUE) {
1535 const char *err = errorString();
1536 d_msg(__FILE__, __LINE__, 99,
1537 "Cannot open file \"%s\" for utime(): ERR=%s", tmpbuf, err);
1538 LocalFree((void *)err);
1539 errno = b_errno_win32;
1543 int rval = SetFileTime(h, NULL, &acc, &mod) ? 0 : -1;
1546 errno = b_errno_win32;
1551 #if USE_WIN32_COMPAT_IO
1554 open(const char *file, int flags, int mode)
1557 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1558 UTF8_2_wchar(&pwszBuf, file);
1560 int nRet = p_wopen((LPCWSTR) pwszBuf, flags|_O_BINARY, mode);
1561 free_pool_memory(pwszBuf);
1566 return _open(file, flags|_O_BINARY, mode);
1570 * Note, this works only for a file. If you want
1571 * to close a socket, use closesocket().
1572 * Bacula has been modified in src/lib/bnet.c
1573 * to use closesocket().
1581 #ifndef HAVE_WXCONSOLE
1583 read(int fd, void *buf, ssize_t len)
1585 return _read(fd, buf, (size_t)len);
1589 write(int fd, const void *buf, ssize_t len)
1591 return _write(fd, buf, (size_t)len);
1597 lseek(int fd, off_t offset, int whence)
1599 return _lseeki64(fd, offset, whence);
1603 dup2(int fd1, int fd2)
1605 return _dup2(fd1, fd2);
1609 open(const char *file, int flags, int mode)
1612 DWORD shareMode = 0;
1615 HANDLE foo = INVALID_HANDLE_VALUE;
1616 const char *remap = file;
1618 if (flags & O_WRONLY) access = GENERIC_WRITE;
1619 else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
1620 else access = GENERIC_READ;
1622 if (flags & O_CREAT) create = CREATE_NEW;
1623 else create = OPEN_EXISTING;
1625 if (flags & O_TRUNC) create = TRUNCATE_EXISTING;
1627 if (!(flags & O_EXCL))
1628 shareMode = FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE;
1630 if (flags & O_APPEND) {
1631 printf("open...APPEND not implemented yet.");
1635 if (p_CreateFileW) {
1636 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1637 UTF8_2_wchar(pwszBuf, file);
1639 foo = p_CreateFileW((LPCWSTR) pwszBuf, access, shareMode, NULL, create, msflags, NULL);
1640 free_pool_memory(pwszBuf);
1642 else if (p_CreateFileA)
1643 foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
1645 if (INVALID_HANDLE_VALUE == foo) {
1646 errno = b_errno_win32;
1657 if (!CloseHandle((HANDLE)fd)) {
1658 errno = b_errno_win32;
1666 write(int fd, const void *data, ssize_t len)
1670 status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
1671 if (status) return bwrite;
1672 errno = b_errno_win32;
1678 read(int fd, void *data, ssize_t len)
1683 status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
1684 if (status) return bread;
1685 errno = b_errno_win32;
1690 lseek(int fd, off_t offset, int whence)
1696 method = FILE_BEGIN;
1699 method = FILE_CURRENT;
1709 if ((val=SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method)) == INVALID_SET_FILE_POINTER) {
1710 errno = b_errno_win32;
1713 /* ***FIXME*** I doubt this works right */
1730 /* syslog function, added by Nicolas Boichat */