2 // compat.cpp -- compatibilty layer to make bacula-fd run
3 // natively under windows
5 // Copyright transferred from Raider Solutions, Inc to
6 // Kern Sibbald and John Walker by express permission.
8 // Copyright (C) 2004-2005 Kern Sibbald
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of
13 // the License, or (at your option) any later version.
15 // This program is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // General Public License for more details.
20 // You should have received a copy of the GNU General Public
21 // License along with this program; if not, write to the Free
22 // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
23 // MA 02111-1307, USA.
25 // Author : Christopher S. Hull
26 // Created On : Sat Jan 31 15:55:00 2004
35 #include "../../lib/winapi.h"
38 /* to allow the usage of the original version in this file here */
41 #define b_errno_win32 (1<<29)
43 #define USE_WIN32_COMPAT_IO 1
45 extern void d_msg(const char *file, int line, int level, const char *fmt,...);
46 extern DWORD g_platform_id;
48 // from MicroSoft SDK (KES) is the diff between Jan 1 1601 and Jan 1 1970
50 #define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000UL //Not sure it works
52 #define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000I64
55 #define WIN32_FILETIME_SCALE 10000000 // 100ns/second
58 cygwin_conv_to_win32_path(const char *name, char *win32_name, DWORD dwSize)
60 const char *fname = name;
61 char *tname = win32_name;
63 /* Check for Unix separator and convert to Win32 */
65 *win32_name++ = '\\'; /* convert char */
66 /* If Win32 separated that is "quoted", remove quote */
67 } else if (*name == '\\' && name[1] == '\\') {
69 name++; /* skip first \ */
71 *win32_name++ = *name; /* copy character */
75 /* Strip any trailing slash, if we stored something */
76 if (*fname != 0 && win32_name[-1] == '\\') {
83 /* here we convert to VSS specific file name which
84 can get longer because VSS will make something like
85 \\\\?\\GLOBALROOT\\Device\\HarddiskVolumeShadowCopy1\\bacula\\uninstall.exe
86 from c:\bacula\uninstall.exe
89 POOLMEM* pszBuf = get_pool_memory (PM_FNAME);
90 pszBuf = check_pool_memory_size(pszBuf, dwSize);
91 bstrncpy (pszBuf, tname, strlen(tname)+1);
92 g_pVSSClient->GetShadowPath(pszBuf,tname,dwSize);
93 free_pool_memory(pszBuf);
99 wchar_2_UTF8(char *pszUTF, const WCHAR *pszUCS, int cchChar)
101 /* the return value is the number of bytes written to the buffer.
102 The number includes the byte for the null terminator. */
104 if (p_WideCharToMultiByte) {
105 int nRet = p_WideCharToMultiByte(CP_UTF8,0,pszUCS,-1,pszUTF,cchChar,NULL,NULL);
114 UTF8_2_wchar(POOLMEM **ppszUCS, const char *pszUTF)
116 /* the return value is the number of wide characters written to the buffer. */
117 /* convert null terminated string from utf-8 to ucs2, enlarge buffer if necessary */
119 if (p_MultiByteToWideChar) {
120 /* strlen of UTF8 +1 is enough */
121 DWORD cchSize = (strlen(pszUTF)+1);
122 *ppszUCS = check_pool_memory_size(*ppszUCS, cchSize*sizeof (WCHAR));
124 int nRet = p_MultiByteToWideChar(CP_UTF8, 0, pszUTF, -1, (LPWSTR) *ppszUCS,cchSize);
134 wchar_win32_path(const char *name, WCHAR *win32_name)
136 const char *fname = name;
138 /* Check for Unix separator and convert to Win32 */
140 *win32_name++ = '\\'; /* convert char */
141 /* If Win32 separated that is "quoted", remove quote */
142 } else if (*name == '\\' && name[1] == '\\') {
143 *win32_name++ = '\\';
144 name++; /* skip first \ */
146 *win32_name++ = *name; /* copy character */
150 /* Strip any trailing slash, if we stored something */
151 if (*fname != 0 && win32_name[-1] == '\\') {
163 int chmod(const char *, mode_t)
168 int chown(const char *k, uid_t, gid_t)
173 int lchown(const char *k, uid_t, gid_t)
179 bool fstype(const char *fname, char *fs, int fslen)
181 return true; /* accept anything */
193 srandom(unsigned int seed)
197 // /////////////////////////////////////////////////////////////////
198 // convert from Windows concept of time to Unix concept of time
199 // /////////////////////////////////////////////////////////////////
201 cvt_utime_to_ftime(const time_t &time, FILETIME &wintime)
203 uint64_t mstime = time;
204 mstime *= WIN32_FILETIME_SCALE;
205 mstime += WIN32_FILETIME_ADJUST;
208 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffUL);
210 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffI64);
212 wintime.dwHighDateTime = (DWORD) ((mstime>>32)& 0xffffffffUL);
216 cvt_ftime_to_utime(const FILETIME &time)
218 uint64_t mstime = time.dwHighDateTime;
220 mstime |= time.dwLowDateTime;
222 mstime -= WIN32_FILETIME_ADJUST;
223 mstime /= WIN32_FILETIME_SCALE; // convert to seconds.
225 return (time_t) (mstime & 0xffffffff);
233 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
234 FORMAT_MESSAGE_FROM_SYSTEM |
235 FORMAT_MESSAGE_IGNORE_INSERTS,
238 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default lang
243 return (const char *) lpMsgBuf;
249 statDir(const char *file, struct stat *sb)
251 WIN32_FIND_DATAW info_w; // window's file info
252 WIN32_FIND_DATAA info_a; // window's file info
254 // cache some common vars to make code more transparent
255 DWORD* pdwFileAttributes;
256 DWORD* pnFileSizeHigh;
257 DWORD* pnFileSizeLow;
258 FILETIME* pftLastAccessTime;
259 FILETIME* pftLastWriteTime;
260 FILETIME* pftCreationTime;
262 if (file[1] == ':' && file[2] == 0) {
263 d_msg(__FILE__, __LINE__, 99, "faking ROOT attrs(%s).\n", file);
264 sb->st_mode = S_IFDIR;
265 sb->st_mode |= S_IREAD|S_IEXEC|S_IWRITE;
272 HANDLE h = INVALID_HANDLE_VALUE;
274 // use unicode or ascii
275 if (p_FindFirstFileW) {
276 POOLMEM* pwszBuf = get_pool_memory (PM_FNAME);
277 UTF8_2_wchar(&pwszBuf, file);
279 h = p_FindFirstFileW((LPCWSTR) pwszBuf, &info_w);
280 free_pool_memory(pwszBuf);
282 pdwFileAttributes = &info_w.dwFileAttributes;
283 pnFileSizeHigh = &info_w.nFileSizeHigh;
284 pnFileSizeLow = &info_w.nFileSizeLow;
285 pftLastAccessTime = &info_w.ftLastAccessTime;
286 pftLastWriteTime = &info_w.ftLastWriteTime;
287 pftCreationTime = &info_w.ftCreationTime;
289 else if (p_FindFirstFileA) {
290 h = p_FindFirstFileA(file, &info_a);
292 pdwFileAttributes = &info_a.dwFileAttributes;
293 pnFileSizeHigh = &info_a.nFileSizeHigh;
294 pnFileSizeLow = &info_a.nFileSizeLow;
295 pftLastAccessTime = &info_a.ftLastAccessTime;
296 pftLastWriteTime = &info_a.ftLastWriteTime;
297 pftCreationTime = &info_a.ftCreationTime;
300 if (h == INVALID_HANDLE_VALUE) {
301 const char *err = errorString();
302 d_msg(__FILE__, __LINE__, 99, "FindFirstFile(%s):%s\n", file, err);
303 LocalFree((void *)err);
304 errno = b_errno_win32;
308 sb->st_mode = 0777; /* start with everything */
309 if (*pdwFileAttributes & FILE_ATTRIBUTE_READONLY)
310 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
311 if (*pdwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
312 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
313 if (*pdwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
314 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
315 sb->st_mode |= S_IFDIR;
317 sb->st_size = *pnFileSizeHigh;
319 sb->st_size |= *pnFileSizeLow;
320 sb->st_blksize = 4096;
321 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
323 sb->st_atime = cvt_ftime_to_utime(*pftLastAccessTime);
324 sb->st_mtime = cvt_ftime_to_utime(*pftLastWriteTime);
325 sb->st_ctime = cvt_ftime_to_utime(*pftCreationTime);
332 stat2(const char *file, struct stat *sb)
334 BY_HANDLE_FILE_INFORMATION info;
338 cygwin_conv_to_win32_path(file, tmpbuf, 1024);
342 if (p_GetFileAttributesW) {
343 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
344 UTF8_2_wchar(&pwszBuf, tmpbuf);
346 attr = p_GetFileAttributesW((LPCWSTR) pwszBuf);
347 free_pool_memory(pwszBuf);
349 else if (p_GetFileAttributesA) {
350 attr = p_GetFileAttributesA(tmpbuf);
354 const char *err = errorString();
355 d_msg(__FILE__, __LINE__, 99,
356 "GetFileAttrubtes(%s): %s\n", tmpbuf, err);
357 LocalFree((void *)err);
358 errno = b_errno_win32;
362 if (attr & FILE_ATTRIBUTE_DIRECTORY)
363 return statDir(tmpbuf, sb);
365 h = CreateFileA(tmpbuf, GENERIC_READ,
366 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
368 if (h == INVALID_HANDLE_VALUE) {
369 const char *err = errorString();
370 d_msg(__FILE__, __LINE__, 99,
371 "Cannot open file for stat (%s):%s\n", tmpbuf, err);
372 LocalFree((void *)err);
374 errno = b_errno_win32;
378 if (!GetFileInformationByHandle(h, &info)) {
379 const char *err = errorString();
380 d_msg(__FILE__, __LINE__, 99,
381 "GetfileInformationByHandle(%s): %s\n", tmpbuf, err);
382 LocalFree((void *)err);
384 errno = b_errno_win32;
388 sb->st_dev = info.dwVolumeSerialNumber;
389 sb->st_ino = info.nFileIndexHigh;
391 sb->st_ino |= info.nFileIndexLow;
392 sb->st_nlink = (short)info.nNumberOfLinks;
393 if (sb->st_nlink > 1) {
394 d_msg(__FILE__, __LINE__, 99, "st_nlink=%d\n", sb->st_nlink);
397 sb->st_mode = 0777; /* start with everything */
398 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
399 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
400 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
401 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
402 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
403 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
404 sb->st_mode |= S_IFREG;
406 sb->st_size = info.nFileSizeHigh;
408 sb->st_size |= info.nFileSizeLow;
409 sb->st_blksize = 4096;
410 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
411 sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
412 sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
413 sb->st_ctime = cvt_ftime_to_utime(info.ftCreationTime);
421 stat(const char *file, struct stat *sb)
423 WIN32_FILE_ATTRIBUTE_DATA data;
427 memset(sb, 0, sizeof(*sb));
429 if (g_platform_id == VER_PLATFORM_WIN32_WINDOWS)
430 return stat2(file, sb);
432 // otherwise we're on NT
440 wchar_win32_path(file, buf+4);
442 if (!GetFileAttributesExW((WCHAR *)buf, GetFileExInfoStandard, &data))
443 return stat2(file, sb);
446 if (p_GetFileAttributesExW) {
447 /* dynamically allocate enough space for UCS2 filename */
448 POOLMEM* pwszBuf = get_pool_memory (PM_FNAME);
449 UTF8_2_wchar(&pwszBuf, file);
451 BOOL b = p_GetFileAttributesExW((LPCWSTR) pwszBuf, GetFileExInfoStandard, &data);
452 free_pool_memory(pwszBuf);
455 return stat2(file, sb);
457 } else if (p_GetFileAttributesExA) {
458 if (!p_GetFileAttributesExA(file, GetFileExInfoStandard, &data))
459 return stat2(file, sb);
462 return stat2(file, sb);
466 sb->st_mode = 0777; /* start with everything */
467 if (data.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
468 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
469 if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
470 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;
480 sb->st_size = data.nFileSizeHigh;
482 sb->st_size |= data.nFileSizeLow;
483 sb->st_blksize = 4096;
484 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
485 sb->st_atime = cvt_ftime_to_utime(data.ftLastAccessTime);
486 sb->st_mtime = cvt_ftime_to_utime(data.ftLastWriteTime);
487 sb->st_ctime = cvt_ftime_to_utime(data.ftCreationTime);
494 lstat(const char *file, struct stat *sb)
496 return stat(file, sb);
512 execvp(const char *, char *[]) {
533 waitpid(int, int*, int)
540 readlink(const char *, char *, int)
549 strcasecmp(const char *s1, const char *s2)
551 register int ch1, ch2;
554 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. */
588 if (ch1 == 0 || tolower(ch1) != tolower(ch2)) break;
595 gettimeofday(struct timeval *tv, struct timezone *)
605 if (!SystemTimeToFileTime(&now, &tmp)) {
606 errno = b_errno_win32;
610 int64_t _100nsec = tmp.dwHighDateTime;
612 _100nsec |= tmp.dwLowDateTime;
613 _100nsec -= WIN32_FILETIME_ADJUST;
615 tv->tv_sec =(long) (_100nsec / 10000000);
616 tv->tv_usec = (long) ((_100nsec % 10000000)/10);
622 syslog(int type, const char *fmt, const char *msg)
624 /*#ifndef HAVE_CONSOLE
625 MessageBox(NULL, msg, "Bacula", MB_OK);
642 // implement opendir/readdir/closedir on top of window's API
646 WIN32_FIND_DATAA data_a; // window's file info (ansii version)
647 WIN32_FIND_DATAW data_w; // window's file info (wchar version)
648 const char *spec; // the directory we're traversing
649 HANDLE dirh; // the search handle
650 BOOL valid_a; // the info in data_a field is valid
651 BOOL valid_w; // the info in data_w field is valid
652 UINT32 offset; // pseudo offset for d_off
656 opendir(const char *path)
658 /* enough space for VSS !*/
659 int max_len = strlen(path) + MAX_PATH;
666 rval = (_dir *)malloc(sizeof(_dir));
667 memset (rval, 0, sizeof (_dir));
668 if (rval == NULL) return NULL;
669 char *tspec = (char *)malloc(max_len);
670 if (tspec == NULL) return NULL;
672 if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS) {
674 /* will append \\?\ at front itself */
675 cygwin_conv_to_win32_path(path, tspec, max_len-4);
677 /* allow path to be 32767 bytes */
683 cygwin_conv_to_win32_path(path, tspec+4, max_len-4);
686 cygwin_conv_to_win32_path(path, tspec, max_len);
689 strncat(tspec, "\\*", max_len);
693 if (p_FindFirstFileW) {
694 POOLMEM* pwcBuf = get_pool_memory(PM_FNAME);;
695 UTF8_2_wchar(&pwcBuf,rval->spec);
696 rval->dirh = p_FindFirstFileW((LPCWSTR)pwcBuf, &rval->data_w);
698 free_pool_memory(pwcBuf);
700 if (rval->dirh != INVALID_HANDLE_VALUE)
702 } else if (p_FindFirstFileA) {
703 rval->dirh = p_FindFirstFileA(rval->spec, &rval->data_a);
705 if (rval->dirh != INVALID_HANDLE_VALUE)
710 d_msg(__FILE__, __LINE__,
711 99, "opendir(%s)\n\tspec=%s,\n\tFindFirstFile returns %d\n",
712 path, rval->spec, rval->dirh);
715 if (rval->dirh == INVALID_HANDLE_VALUE)
719 d_msg(__FILE__, __LINE__,
720 99, "\tFirstFile=%s\n", rval->data_w.cFileName);
723 d_msg(__FILE__, __LINE__,
724 99, "\tFirstFile=%s\n", rval->data_a.cFileName);
729 free((void *)rval->spec);
731 errno = b_errno_win32;
738 _dir *dp = (_dir *)dirp;
740 free((void *)dp->spec);
746 typedef struct _WIN32_FIND_DATA {
747 DWORD dwFileAttributes;
748 FILETIME ftCreationTime;
749 FILETIME ftLastAccessTime;
750 FILETIME ftLastWriteTime;
755 TCHAR cFileName[MAX_PATH];
756 TCHAR cAlternateFileName[14];
757 } WIN32_FIND_DATA, *PWIN32_FIND_DATA;
761 copyin(struct dirent &dp, const char *fname)
765 char *cp = dp.d_name;
775 readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
777 _dir *dp = (_dir *)dirp;
778 if (dp->valid_w || dp->valid_a) {
779 entry->d_off = dp->offset;
783 char szBuf[MAX_PATH_UTF8];
784 wchar_2_UTF8(szBuf,dp->data_w.cFileName);
785 dp->offset += copyin(*entry, szBuf);
786 } else if (dp->valid_a) { // copy ansi (only 1 will be valid)
787 dp->offset += copyin(*entry, dp->data_a.cFileName);
790 *result = entry; /* return entry address */
791 d_msg(__FILE__, __LINE__,
792 99, "readdir_r(%p, { d_name=\"%s\", d_reclen=%d, d_off=%d\n",
793 dirp, entry->d_name, entry->d_reclen, entry->d_off);
795 // d_msg(__FILE__, __LINE__, 99, "readdir_r !valid\n");
796 errno = b_errno_win32;
800 // get next file, try unicode first
802 dp->valid_w = p_FindNextFileW(dp->dirh, &dp->data_w);
803 else if (p_FindNextFileA)
804 dp->valid_a = p_FindNextFileA(dp->dirh, &dp->data_a);
814 * Dotted IP address to network address
820 inet_aton(const char *a, struct in_addr *inp)
823 uint32_t acc = 0, tmp = 0;
826 if (!isdigit(*cp)) { /* first char must be digit */
827 return 0; /* error */
831 tmp = (tmp * 10) + (*cp -'0');
832 } else if (*cp == '.' || *cp == 0) {
834 return 0; /* error */
836 acc = (acc << 8) + tmp;
840 return 0; /* error */
842 } while (*cp++ != 0);
843 if (dotc != 4) { /* want 3 .'s plus EOS */
844 return 0; /* error */
846 inp->s_addr = htonl(acc); /* store addr in network format */
851 nanosleep(const struct timespec *req, struct timespec *rem)
854 rem->tv_sec = rem->tv_nsec = 0;
855 Sleep((req->tv_sec * 1000) + (req->tv_nsec/100000));
860 init_signals(void terminate(int sig))
866 init_stack_dump(void)
873 pathconf(const char *path, int name)
877 if (strncmp(path, "\\\\?\\", 4) == 0)
889 WORD wVersionRequested = MAKEWORD( 1, 1);
892 int err = WSAStartup(wVersionRequested, &wsaData);
896 printf("Can not start Windows Sockets\n");
906 win32_chdir(const char *dir)
908 if (p_SetCurrentDirectoryW) {
909 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
910 UTF8_2_wchar(&pwszBuf, dir);
912 BOOL b=p_SetCurrentDirectoryW((LPCWSTR)pwszBuf);
913 free_pool_memory(pwszBuf);
916 errno = b_errno_win32;
920 else if (p_SetCurrentDirectoryA) {
921 if (0 == p_SetCurrentDirectoryA(dir)) {
922 errno = b_errno_win32;
932 win32_mkdir(const char *dir)
935 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
936 UTF8_2_wchar(&pwszBuf, dir);
938 int n=p_wmkdir((LPCWSTR)pwszBuf);
939 free_pool_memory(pwszBuf);
948 win32_getcwd(char *buf, int maxlen)
952 if (p_GetCurrentDirectoryW) {
953 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
954 pwszBuf = check_pool_memory_size (pwszBuf, maxlen*sizeof(WCHAR));
956 n = p_GetCurrentDirectoryW(maxlen, (LPWSTR) pwszBuf);
957 n = wchar_2_UTF8 (buf, (WCHAR*)pwszBuf, maxlen)-1;
958 free_pool_memory(pwszBuf);
960 } else if (p_GetCurrentDirectoryA)
961 n = p_GetCurrentDirectoryA(maxlen, buf);
963 if (n == 0 || n > maxlen) return NULL;
965 if (n+1 > maxlen) return NULL;
974 win32_fputs(const char *string, FILE *stream)
976 /* we use WriteConsoleA / WriteConsoleA
977 so we can be sure that unicode support works on win32.
978 with fallback if something fails
981 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
982 if (hOut && (hOut != INVALID_HANDLE_VALUE) && p_WideCharToMultiByte &&
983 p_MultiByteToWideChar && (stream == stdout)) {
985 POOLMEM* pwszBuf = get_pool_memory(PM_MESSAGE);
987 DWORD dwCharsWritten;
990 dwChars = UTF8_2_wchar(&pwszBuf, string);
992 /* try WriteConsoleW */
993 if (WriteConsoleW (hOut, pwszBuf, dwChars-1, &dwCharsWritten, NULL)) {
994 free_pool_memory(pwszBuf);
995 return dwCharsWritten;
998 /* convert to local codepage and try WriteConsoleA */
999 POOLMEM* pszBuf = get_pool_memory(PM_MESSAGE);
1000 pszBuf = check_pool_memory_size(pszBuf, dwChars+1);
1002 dwChars = p_WideCharToMultiByte(GetConsoleOutputCP(),0,(LPCWSTR) pwszBuf,-1,pszBuf,dwChars,NULL,NULL);
1003 free_pool_memory(pwszBuf);
1005 if (WriteConsoleA (hOut, pszBuf, dwChars-1, &dwCharsWritten, NULL)) {
1006 free_pool_memory(pszBuf);
1007 return dwCharsWritten;
1011 return fputs(string, stream);
1015 win32_cgets (char* buffer, int len)
1017 /* we use console ReadConsoleA / ReadConsoleW to be able to read unicode
1018 from the win32 console and fallback if seomething fails */
1020 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
1021 if (hIn && (hIn != INVALID_HANDLE_VALUE) && p_WideCharToMultiByte && p_MultiByteToWideChar) {
1026 /* nt and unicode conversion */
1027 if (ReadConsoleW (hIn, wszBuf, 1024, &dwRead, NULL)) {
1029 /* null terminate at end */
1030 if (wszBuf[dwRead-1] == L'\n') {
1031 wszBuf[dwRead-1] = L'\0';
1035 if (wszBuf[dwRead-1] == L'\r') {
1036 wszBuf[dwRead-1] = L'\0';
1040 wchar_2_UTF8(buffer, wszBuf, len);
1044 /* win 9x and unicode conversion */
1045 if (ReadConsoleA (hIn, szBuf, 1024, &dwRead, NULL)) {
1047 /* null terminate at end */
1048 if (szBuf[dwRead-1] == L'\n') {
1049 szBuf[dwRead-1] = L'\0';
1053 if (szBuf[dwRead-1] == L'\r') {
1054 szBuf[dwRead-1] = L'\0';
1058 /* convert from ansii to WCHAR */
1059 p_MultiByteToWideChar(GetConsoleCP(), 0, szBuf, -1, wszBuf,1024);
1060 /* convert from WCHAR to UTF-8 */
1061 if (wchar_2_UTF8(buffer, wszBuf, len))
1067 if (fgets(buffer, len, stdin))
1074 win32_unlink(const char *filename)
1078 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1079 UTF8_2_wchar(&pwszBuf, filename);
1080 nRetCode = _wunlink((LPCWSTR) pwszBuf);
1081 free_pool_memory(pwszBuf);
1083 nRetCode = _unlink(filename);
1089 #include "mswinver.h"
1091 char WIN_VERSION_LONG[64];
1092 char WIN_VERSION[32];
1099 static winver INIT; // cause constructor to be called before main()
1104 winver::winver(void)
1106 const char *version = "";
1107 const char *platform = "";
1108 OSVERSIONINFO osvinfo;
1109 osvinfo.dwOSVersionInfoSize = sizeof(osvinfo);
1111 // Get the current OS version
1112 if (!GetVersionEx(&osvinfo)) {
1113 version = "Unknown";
1114 platform = "Unknown";
1117 switch (_mkversion(osvinfo.dwPlatformId, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion))
1119 case MS_WINDOWS_95: (version = "Windows 95"); break;
1120 case MS_WINDOWS_98: (version = "Windows 98"); break;
1121 case MS_WINDOWS_ME: (version = "Windows ME"); break;
1122 case MS_WINDOWS_NT4:(version = "Windows NT 4.0"); platform = "NT"; break;
1123 case MS_WINDOWS_2K: (version = "Windows 2000");platform = "NT"; break;
1124 case MS_WINDOWS_XP: (version = "Windows XP");platform = "NT"; break;
1125 case MS_WINDOWS_S2003: (version = "Windows Server 2003");platform = "NT"; break;
1126 default: version = "Windows ??"; break;
1129 bstrncpy(WIN_VERSION_LONG, version, sizeof(WIN_VERSION_LONG));
1130 snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %d.%d.%d",
1131 platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
1134 HANDLE h = CreateFile("G:\\foobar", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
1138 BPIPE *b = open_bpipe("ls -l", 10, "r");
1140 while (!feof(b->rfd)) {
1141 fgets(buf, sizeof(buf), b->rfd);
1147 BOOL CreateChildProcess(VOID);
1148 VOID WriteToPipe(VOID);
1149 VOID ReadFromPipe(VOID);
1150 VOID ErrorExit(LPCSTR);
1151 VOID ErrMsg(LPTSTR, BOOL);
1154 * Check for a quoted path, if an absolute path name is given and it contains
1155 * spaces it will need to be quoted. i.e. "c:/Program Files/foo/bar.exe"
1156 * CreateProcess() says the best way to ensure proper results with executables
1157 * with spaces in path or filename is to quote the string.
1160 getArgv0(const char *cmdline)
1164 for (const char *cp = cmdline; *cp; cp++)
1169 if (!inquote && isspace(*cp))
1174 int len = cp - cmdline;
1175 char *rval = (char *)malloc(len+1);
1189 * OK, so it would seem CreateProcess only handles true executables:
1190 * .com or .exe files.
1191 * So test to see whether we're getting a .bat file and if so grab
1192 * $COMSPEC value and pass batch file to it.
1195 CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err)
1197 PROCESS_INFORMATION piProcInfo;
1198 STARTUPINFOA siStartInfo;
1199 BOOL bFuncRetn = FALSE;
1201 // Set up members of the PROCESS_INFORMATION structure.
1203 ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
1205 // Set up members of the STARTUPINFO structure.
1207 ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
1208 siStartInfo.cb = sizeof(STARTUPINFO);
1209 // setup new process to use supplied handles for stdin,stdout,stderr
1210 // if supplied handles are not used the send a copy of our STD_HANDLE
1212 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
1214 if (in != INVALID_HANDLE_VALUE)
1215 siStartInfo.hStdInput = in;
1217 siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1219 if (out != INVALID_HANDLE_VALUE)
1220 siStartInfo.hStdOutput = out;
1222 siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1223 if (err != INVALID_HANDLE_VALUE)
1224 siStartInfo.hStdError = err;
1226 siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1227 // Create the child process.
1231 const char *comspec = getenv("COMSPEC");
1233 if (comspec == NULL) // should never happen
1234 return INVALID_HANDLE_VALUE;
1236 char *cmdLine = (char *)alloca(strlen(cmdline) + strlen(comspec) + 16);
1238 strcpy(exeFile, comspec);
1239 strcpy(cmdLine, comspec);
1240 strcat(cmdLine, " /c ");
1241 strcat(cmdLine, cmdline);
1243 // try to execute program
1244 bFuncRetn = CreateProcessA(exeFile,
1245 cmdLine, // command line
1246 NULL, // process security attributes
1247 NULL, // primary thread security attributes
1248 TRUE, // handles are inherited
1249 0, // creation flags
1250 NULL, // use parent's environment
1251 NULL, // use parent's current directory
1252 &siStartInfo, // STARTUPINFO pointer
1253 &piProcInfo); // receives PROCESS_INFORMATION
1255 if (bFuncRetn == 0) {
1256 ErrorExit("CreateProcess failed\n");
1257 const char *err = errorString();
1258 d_msg(__FILE__, __LINE__, 99,
1259 "CreateProcess(%s, %s, ...)=%s\n", exeFile, cmdLine, err);
1260 LocalFree((void *)err);
1261 return INVALID_HANDLE_VALUE;
1263 // we don't need a handle on the process primary thread so we close
1265 CloseHandle(piProcInfo.hThread);
1267 return piProcInfo.hProcess;
1272 ErrorExit (LPCSTR lpszMessage)
1274 d_msg(__FILE__, __LINE__, 0, "%s", lpszMessage);
1279 typedef struct s_bpipe {
1281 time_t worker_stime;
1290 CloseIfValid(HANDLE handle)
1292 if (handle != INVALID_HANDLE_VALUE)
1293 CloseHandle(handle);
1298 open_bpipe(char *prog, int wait, const char *mode)
1300 HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
1301 hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup,
1304 SECURITY_ATTRIBUTES saAttr;
1308 hChildStdinRd = hChildStdinWr = hChildStdinWrDup =
1309 hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup =
1310 hInputFile = INVALID_HANDLE_VALUE;
1312 BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
1313 memset((void *)bpipe, 0, sizeof(BPIPE));
1315 int mode_read = (mode[0] == 'r');
1316 int mode_write = (mode[0] == 'w' || mode[1] == 'w');
1319 // Set the bInheritHandle flag so pipe handles are inherited.
1321 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1322 saAttr.bInheritHandle = TRUE;
1323 saAttr.lpSecurityDescriptor = NULL;
1327 // Create a pipe for the child process's STDOUT.
1328 if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
1329 ErrorExit("Stdout pipe creation failed\n");
1332 // Create noninheritable read handle and close the inheritable read
1335 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
1336 GetCurrentProcess(), &hChildStdoutRdDup , 0,
1338 DUPLICATE_SAME_ACCESS);
1340 ErrorExit("DuplicateHandle failed");
1344 CloseHandle(hChildStdoutRd);
1345 hChildStdoutRd = INVALID_HANDLE_VALUE;
1350 // Create a pipe for the child process's STDIN.
1352 if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
1353 ErrorExit("Stdin pipe creation failed\n");
1357 // Duplicate the write handle to the pipe so it is not inherited.
1358 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
1359 GetCurrentProcess(), &hChildStdinWrDup,
1361 FALSE, // not inherited
1362 DUPLICATE_SAME_ACCESS);
1364 ErrorExit("DuplicateHandle failed");
1368 CloseHandle(hChildStdinWr);
1369 hChildStdinWr = INVALID_HANDLE_VALUE;
1371 // spawn program with redirected handles as appropriate
1372 bpipe->worker_pid = (pid_t)
1373 CreateChildProcess(prog, // commandline
1374 hChildStdinRd, // stdin HANDLE
1375 hChildStdoutWr, // stdout HANDLE
1376 hChildStdoutWr); // stderr HANDLE
1378 if ((HANDLE) bpipe->worker_pid == INVALID_HANDLE_VALUE)
1382 bpipe->worker_stime = time(NULL);
1385 CloseHandle(hChildStdoutWr); // close our write side so when
1386 // process terminates we can
1388 // ugly but convert WIN32 HANDLE to FILE*
1389 int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
1391 bpipe->rfd = _fdopen(rfd, "r");
1395 CloseHandle(hChildStdinRd); // close our read side so as not
1396 // to interfre with child's copy
1397 // ugly but convert WIN32 HANDLE to FILE*
1398 int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
1400 bpipe->wfd = _fdopen(wfd, "w");
1405 bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
1412 CloseIfValid(hChildStdoutRd);
1413 CloseIfValid(hChildStdoutRdDup);
1414 CloseIfValid(hChildStdinWr);
1415 CloseIfValid(hChildStdinWrDup);
1417 free((void *) bpipe);
1418 errno = b_errno_win32; /* do GetLastError() for error code */
1425 kill(int pid, int signal)
1428 if (!TerminateProcess((HANDLE)pid, (UINT) signal)) {
1430 errno = b_errno_win32;
1432 CloseHandle((HANDLE)pid);
1439 close_bpipe(BPIPE *bpipe)
1442 int32_t remaining_wait = bpipe->wait;
1444 if (remaining_wait == 0) { /* wait indefinitely */
1445 remaining_wait = INT32_MAX;
1449 if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode)) {
1450 const char *err = errorString();
1451 rval = b_errno_win32;
1452 d_msg(__FILE__, __LINE__, 0,
1453 "GetExitCode error %s\n", err);
1454 LocalFree((void *)err);
1457 if (exitCode == STILL_ACTIVE) {
1458 if (remaining_wait <= 0) {
1459 rval = ETIME; /* timed out */
1462 bmicrosleep(1, 0); /* wait one second */
1464 } else if (exitCode != 0) {
1465 /* Truncate exit code as it doesn't seem to be correct */
1466 rval = (exitCode & 0xFF) | b_errno_exit;
1469 break; /* Shouldn't get here */
1473 if (bpipe->timer_id) {
1474 stop_child_timer(bpipe->timer_id);
1476 if (bpipe->rfd) fclose(bpipe->rfd);
1477 if (bpipe->wfd) fclose(bpipe->wfd);
1478 free((void *)bpipe);
1483 close_wpipe(BPIPE *bpipe)
1489 if (fclose(bpipe->wfd) != 0) {
1497 #include "findlib/find.h"
1500 utime(const char *fname, struct utimbuf *times)
1505 cygwin_conv_to_win32_path(fname, tmpbuf, 1024);
1507 cvt_utime_to_ftime(times->actime, acc);
1508 cvt_utime_to_ftime(times->modtime, mod);
1510 HANDLE h = INVALID_HANDLE_VALUE;
1512 if (p_CreateFileW) {
1513 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1514 UTF8_2_wchar(&pwszBuf, tmpbuf);
1516 h = p_CreateFileW((LPCWSTR) pwszBuf,
1517 FILE_WRITE_ATTRIBUTES,
1524 free_pool_memory(pwszBuf);
1525 } else if (p_CreateFileA) {
1526 h = p_CreateFileA(tmpbuf,
1527 FILE_WRITE_ATTRIBUTES,
1535 if (h == INVALID_HANDLE_VALUE) {
1536 const char *err = errorString();
1537 d_msg(__FILE__, __LINE__, 99,
1538 "Cannot open file \"%s\" for utime(): ERR=%s", tmpbuf, err);
1539 LocalFree((void *)err);
1540 errno = b_errno_win32;
1544 int rval = SetFileTime(h, NULL, &acc, &mod) ? 0 : -1;
1547 errno = b_errno_win32;
1552 #if USE_WIN32_COMPAT_IO
1555 open(const char *file, int flags, int mode)
1558 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1559 UTF8_2_wchar(&pwszBuf, file);
1561 int nRet = p_wopen((LPCWSTR) pwszBuf, flags|_O_BINARY, mode);
1562 free_pool_memory(pwszBuf);
1567 return _open(file, flags|_O_BINARY, mode);
1571 * Note, this works only for a file. If you want
1572 * to close a socket, use closesocket().
1573 * Bacula has been modified in src/lib/bnet.c
1574 * to use closesocket().
1582 #ifndef HAVE_WXCONSOLE
1584 read(int fd, void *buf, ssize_t len)
1586 return _read(fd, buf, (size_t)len);
1590 write(int fd, const void *buf, ssize_t len)
1592 return _write(fd, buf, (size_t)len);
1598 lseek(int fd, off_t offset, int whence)
1600 return _lseeki64(fd, offset, whence);
1604 dup2(int fd1, int fd2)
1606 return _dup2(fd1, fd2);
1610 open(const char *file, int flags, int mode)
1613 DWORD shareMode = 0;
1616 HANDLE foo = INVALID_HANDLE_VALUE;
1617 const char *remap = file;
1619 if (flags & O_WRONLY) access = GENERIC_WRITE;
1620 else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
1621 else access = GENERIC_READ;
1623 if (flags & O_CREAT) create = CREATE_NEW;
1624 else create = OPEN_EXISTING;
1626 if (flags & O_TRUNC) create = TRUNCATE_EXISTING;
1628 if (!(flags & O_EXCL))
1629 shareMode = FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE;
1631 if (flags & O_APPEND) {
1632 printf("open...APPEND not implemented yet.");
1636 if (p_CreateFileW) {
1637 POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1638 UTF8_2_wchar(pwszBuf, file);
1640 foo = p_CreateFileW((LPCWSTR) pwszBuf, access, shareMode, NULL, create, msflags, NULL);
1641 free_pool_memory(pwszBuf);
1643 else if (p_CreateFileA)
1644 foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
1646 if (INVALID_HANDLE_VALUE == foo) {
1647 errno = b_errno_win32;
1658 if (!CloseHandle((HANDLE)fd)) {
1659 errno = b_errno_win32;
1667 write(int fd, const void *data, ssize_t len)
1671 status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
1672 if (status) return bwrite;
1673 errno = b_errno_win32;
1679 read(int fd, void *data, ssize_t len)
1684 status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
1685 if (status) return bread;
1686 errno = b_errno_win32;
1691 lseek(int fd, off_t offset, int whence)
1697 method = FILE_BEGIN;
1700 method = FILE_CURRENT;
1710 if ((val=SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method)) == INVALID_SET_FILE_POINTER) {
1711 errno = b_errno_win32;
1714 /* ***FIXME*** I doubt this works right */
1731 /* syslog function, added by Nicolas Boichat */