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
36 #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 */
84 char szFile[MAX_PATH_UNICODE];
85 strncpy (szFile, tname, MAX_PATH_UNICODE-1);
86 g_VSSClient.GetShadowPath(szFile,tname,dwSize);
91 wchar_2_UTF8(char *pszUTF, const WCHAR *pszUCS, int cchChar)
93 /* the return value is the number of bytes written to the buffer.
94 The number includes the byte for the null terminator. */
96 if (p_WideCharToMultiByte)
97 return p_WideCharToMultiByte(CP_UTF8,0,pszUCS,-1,pszUTF,cchChar,NULL,NULL);
103 UTF8_2_wchar(WCHAR *pszUCS, const char *pszUTF, int cchWideChar)
105 /* the return value is the number of wide characters written to the buffer. */
106 /* convert null terminated string from utf-8 to ucs2*/
108 if (p_MultiByteToWideChar)
109 return p_MultiByteToWideChar(CP_UTF8, 0, pszUTF, -1, pszUCS,cchWideChar);
116 wchar_win32_path(const char *name, WCHAR *win32_name)
118 const char *fname = name;
120 /* Check for Unix separator and convert to Win32 */
122 *win32_name++ = '\\'; /* convert char */
123 /* If Win32 separated that is "quoted", remove quote */
124 } else if (*name == '\\' && name[1] == '\\') {
125 *win32_name++ = '\\';
126 name++; /* skip first \ */
128 *win32_name++ = *name; /* copy character */
132 /* Strip any trailing slash, if we stored something */
133 if (*fname != 0 && win32_name[-1] == '\\') {
145 int chmod(const char *, mode_t)
150 int chown(const char *k, uid_t, gid_t)
155 int lchown(const char *k, uid_t, gid_t)
161 bool fstype(const char *fname, char *fs, int fslen)
163 return true; /* accept anything */
175 srandom(unsigned int seed)
179 // /////////////////////////////////////////////////////////////////
180 // convert from Windows concept of time to Unix concept of time
181 // /////////////////////////////////////////////////////////////////
183 cvt_utime_to_ftime(const time_t &time, FILETIME &wintime)
185 uint64_t mstime = time;
186 mstime *= WIN32_FILETIME_SCALE;
187 mstime += WIN32_FILETIME_ADJUST;
190 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffUL);
192 wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffI64);
194 wintime.dwHighDateTime = (DWORD) ((mstime>>32)& 0xffffffffUL);
198 cvt_ftime_to_utime(const FILETIME &time)
200 uint64_t mstime = time.dwHighDateTime;
202 mstime |= time.dwLowDateTime;
204 mstime -= WIN32_FILETIME_ADJUST;
205 mstime /= WIN32_FILETIME_SCALE; // convert to seconds.
207 return (time_t) (mstime & 0xffffffff);
215 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
216 FORMAT_MESSAGE_FROM_SYSTEM |
217 FORMAT_MESSAGE_IGNORE_INSERTS,
220 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default lang
225 return (const char *) lpMsgBuf;
231 statDir(const char *file, struct stat *sb)
233 WIN32_FIND_DATAW info_w; // window's file info
234 WIN32_FIND_DATAA info_a; // window's file info
236 // cache some common vars to make code more transparent
237 DWORD* pdwFileAttributes;
238 DWORD* pnFileSizeHigh;
239 DWORD* pnFileSizeLow;
240 FILETIME* pftLastAccessTime;
241 FILETIME* pftLastWriteTime;
242 FILETIME* pftCreationTime;
244 if (file[1] == ':' && file[2] == 0) {
245 d_msg(__FILE__, __LINE__, 99, "faking ROOT attrs(%s).\n", file);
246 sb->st_mode = S_IFDIR;
247 sb->st_mode |= S_IREAD|S_IEXEC|S_IWRITE;
254 HANDLE h = INVALID_HANDLE_VALUE;
256 // use unicode or ascii
257 if (p_FindFirstFileW) {
258 WCHAR szBuf[MAX_PATH_UNICODE];
259 UTF8_2_wchar(szBuf, file, MAX_PATH_UNICODE);
261 h = p_FindFirstFileW(szBuf, &info_w);
263 pdwFileAttributes = &info_w.dwFileAttributes;
264 pnFileSizeHigh = &info_w.nFileSizeHigh;
265 pnFileSizeLow = &info_w.nFileSizeLow;
266 pftLastAccessTime = &info_w.ftLastAccessTime;
267 pftLastWriteTime = &info_w.ftLastWriteTime;
268 pftCreationTime = &info_w.ftCreationTime;
270 else if (p_FindFirstFileA) {
271 h = p_FindFirstFileA(file, &info_a);
273 pdwFileAttributes = &info_a.dwFileAttributes;
274 pnFileSizeHigh = &info_a.nFileSizeHigh;
275 pnFileSizeLow = &info_a.nFileSizeLow;
276 pftLastAccessTime = &info_a.ftLastAccessTime;
277 pftLastWriteTime = &info_a.ftLastWriteTime;
278 pftCreationTime = &info_a.ftCreationTime;
281 if (h == INVALID_HANDLE_VALUE) {
282 const char *err = errorString();
283 d_msg(__FILE__, __LINE__, 99, "FindFirstFile(%s):%s\n", file, err);
284 LocalFree((void *)err);
285 errno = b_errno_win32;
289 sb->st_mode = 0777; /* start with everything */
290 if (*pdwFileAttributes & FILE_ATTRIBUTE_READONLY)
291 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
292 if (*pdwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
293 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
294 if (*pdwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
295 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
296 sb->st_mode |= S_IFDIR;
298 sb->st_size = *pnFileSizeHigh;
300 sb->st_size |= *pnFileSizeLow;
301 sb->st_blksize = 4096;
302 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
304 sb->st_atime = cvt_ftime_to_utime(*pftLastAccessTime);
305 sb->st_mtime = cvt_ftime_to_utime(*pftLastWriteTime);
306 sb->st_ctime = cvt_ftime_to_utime(*pftCreationTime);
313 stat2(const char *file, struct stat *sb)
315 BY_HANDLE_FILE_INFORMATION info;
319 cygwin_conv_to_win32_path(file, tmpbuf, 1024);
323 if (p_GetFileAttributesW) {
324 WCHAR szBuf[MAX_PATH_UNICODE];
325 UTF8_2_wchar(szBuf, tmpbuf, MAX_PATH_UNICODE);
327 attr = p_GetFileAttributesW(szBuf);
329 else if (p_GetFileAttributesA) {
330 attr = p_GetFileAttributesA(tmpbuf);
334 const char *err = errorString();
335 d_msg(__FILE__, __LINE__, 99,
336 "GetFileAttrubtes(%s): %s\n", tmpbuf, err);
337 LocalFree((void *)err);
338 errno = b_errno_win32;
342 if (attr & FILE_ATTRIBUTE_DIRECTORY)
343 return statDir(tmpbuf, sb);
345 h = CreateFileA(tmpbuf, GENERIC_READ,
346 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
348 if (h == INVALID_HANDLE_VALUE) {
349 const char *err = errorString();
350 d_msg(__FILE__, __LINE__, 99,
351 "Cannot open file for stat (%s):%s\n", tmpbuf, err);
352 LocalFree((void *)err);
354 errno = b_errno_win32;
358 if (!GetFileInformationByHandle(h, &info)) {
359 const char *err = errorString();
360 d_msg(__FILE__, __LINE__, 99,
361 "GetfileInformationByHandle(%s): %s\n", tmpbuf, err);
362 LocalFree((void *)err);
364 errno = b_errno_win32;
368 sb->st_dev = info.dwVolumeSerialNumber;
369 sb->st_ino = info.nFileIndexHigh;
371 sb->st_ino |= info.nFileIndexLow;
372 sb->st_nlink = (short)info.nNumberOfLinks;
373 if (sb->st_nlink > 1) {
374 d_msg(__FILE__, __LINE__, 99, "st_nlink=%d\n", sb->st_nlink);
377 sb->st_mode = 0777; /* start with everything */
378 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
379 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
380 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
381 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
382 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
383 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
384 sb->st_mode |= S_IFREG;
386 sb->st_size = info.nFileSizeHigh;
388 sb->st_size |= info.nFileSizeLow;
389 sb->st_blksize = 4096;
390 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
391 sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
392 sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
393 sb->st_ctime = cvt_ftime_to_utime(info.ftCreationTime);
401 stat(const char *file, struct stat *sb)
403 WIN32_FILE_ATTRIBUTE_DATA data;
407 memset(sb, 0, sizeof(*sb));
409 if (g_platform_id == VER_PLATFORM_WIN32_WINDOWS)
410 return stat2(file, sb);
412 // otherwise we're on NT
420 wchar_win32_path(file, buf+4);
422 if (!GetFileAttributesExW((WCHAR *)buf, GetFileExInfoStandard, &data))
423 return stat2(file, sb);
426 if (p_GetFileAttributesExW) {
427 WCHAR buf[MAX_PATH_UNICODE];
428 UTF8_2_wchar(buf, file, MAX_PATH_UNICODE);
429 if (!p_GetFileAttributesExW(buf, GetFileExInfoStandard, &data))
430 return stat2(file, sb);
431 } else if (p_GetFileAttributesExA) {
432 if (!p_GetFileAttributesExA(file, GetFileExInfoStandard, &data))
433 return stat2(file, sb);
436 return stat2(file, sb);
440 sb->st_mode = 0777; /* start with everything */
441 if (data.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
442 sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
443 if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
444 sb->st_mode &= ~S_IRWXO; /* remove everything for other */
445 if (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
446 sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
448 if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
449 sb->st_mode |= S_IFDIR;
451 sb->st_mode |= S_IFREG;
454 sb->st_size = data.nFileSizeHigh;
456 sb->st_size |= data.nFileSizeLow;
457 sb->st_blksize = 4096;
458 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
459 sb->st_atime = cvt_ftime_to_utime(data.ftLastAccessTime);
460 sb->st_mtime = cvt_ftime_to_utime(data.ftLastWriteTime);
461 sb->st_ctime = cvt_ftime_to_utime(data.ftCreationTime);
468 lstat(const char *file, struct stat *sb)
470 return stat(file, sb);
486 execvp(const char *, char *[]) {
507 waitpid(int, int*, int)
514 readlink(const char *, char *, int)
523 strcasecmp(const char *s1, const char *s2)
525 register int ch1, ch2;
528 return 0; /* strings are equal if same object. */
539 } while (ch1 != 0 && tolower(ch1) == tolower(ch2));
546 strncasecmp(const char *s1, const char *s2, int len)
548 register int ch1, ch2;
551 return 0; /* strings are equal if same object. */
562 if (ch1 == 0 || tolower(ch1) != tolower(ch2)) break;
569 gettimeofday(struct timeval *tv, struct timezone *)
579 if (!SystemTimeToFileTime(&now, &tmp)) {
580 errno = b_errno_win32;
584 int64_t _100nsec = tmp.dwHighDateTime;
586 _100nsec |= tmp.dwLowDateTime;
587 _100nsec -= WIN32_FILETIME_ADJUST;
589 tv->tv_sec =(long) (_100nsec / 10000000);
590 tv->tv_usec = (long) ((_100nsec % 10000000)/10);
596 syslog(int type, const char *fmt, const char *msg)
598 /*#ifndef HAVE_CONSOLE
599 MessageBox(NULL, msg, "Bacula", MB_OK);
616 // implement opendir/readdir/closedir on top of window's API
620 WIN32_FIND_DATAA data_a; // window's file info (ansii version)
621 WIN32_FIND_DATAW data_w; // window's file info (wchar version)
622 const char *spec; // the directory we're traversing
623 HANDLE dirh; // the search handle
624 BOOL valid_a; // the info in data_a field is valid
625 BOOL valid_w; // the info in data_w field is valid
626 UINT32 offset; // pseudo offset for d_off
630 opendir(const char *path)
632 /* enough space for VSS !*/
633 int max_len = strlen(path) + MAX_PATH;
640 rval = (_dir *)malloc(sizeof(_dir));
641 memset (rval, 0, sizeof (_dir));
642 if (rval == NULL) return NULL;
643 char *tspec = (char *)malloc(max_len);
644 if (tspec == NULL) return NULL;
646 if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS) {
647 // allow path to be 32767 bytes
653 cygwin_conv_to_win32_path(path, tspec+4, max_len-4);
655 cygwin_conv_to_win32_path(path, tspec, max_len);
658 strncat(tspec, "\\*", max_len);
662 if (p_FindFirstFileW) {
663 WCHAR wcBuf[MAX_PATH_UNICODE];
664 UTF8_2_wchar(wcBuf,rval->spec, MAX_PATH_UNICODE);
665 rval->dirh = p_FindFirstFileW(wcBuf, &rval->data_w);
667 if (rval->dirh != INVALID_HANDLE_VALUE)
669 } else if (p_FindFirstFileA) {
670 rval->dirh = p_FindFirstFileA(rval->spec, &rval->data_a);
672 if (rval->dirh != INVALID_HANDLE_VALUE)
677 d_msg(__FILE__, __LINE__,
678 99, "opendir(%s)\n\tspec=%s,\n\tFindFirstFile returns %d\n",
679 path, rval->spec, rval->dirh);
682 if (rval->dirh == INVALID_HANDLE_VALUE)
686 d_msg(__FILE__, __LINE__,
687 99, "\tFirstFile=%s\n", rval->data_w.cFileName);
690 d_msg(__FILE__, __LINE__,
691 99, "\tFirstFile=%s\n", rval->data_a.cFileName);
696 free((void *)rval->spec);
698 errno = b_errno_win32;
705 _dir *dp = (_dir *)dirp;
707 free((void *)dp->spec);
713 typedef struct _WIN32_FIND_DATA {
714 DWORD dwFileAttributes;
715 FILETIME ftCreationTime;
716 FILETIME ftLastAccessTime;
717 FILETIME ftLastWriteTime;
722 TCHAR cFileName[MAX_PATH];
723 TCHAR cAlternateFileName[14];
724 } WIN32_FIND_DATA, *PWIN32_FIND_DATA;
728 copyin(struct dirent &dp, const char *fname)
732 char *cp = dp.d_name;
742 readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
744 _dir *dp = (_dir *)dirp;
745 if (dp->valid_w || dp->valid_a) {
746 entry->d_off = dp->offset;
750 char szBuf[MAX_PATH_UTF8];
751 wchar_2_UTF8(szBuf,dp->data_w.cFileName);
752 dp->offset += copyin(*entry, szBuf);
753 } else if (dp->valid_a) { // copy ansi (only 1 will be valid)
754 dp->offset += copyin(*entry, dp->data_a.cFileName);
757 *result = entry; /* return entry address */
758 d_msg(__FILE__, __LINE__,
759 99, "readdir_r(%p, { d_name=\"%s\", d_reclen=%d, d_off=%d\n",
760 dirp, entry->d_name, entry->d_reclen, entry->d_off);
762 // d_msg(__FILE__, __LINE__, 99, "readdir_r !valid\n");
763 errno = b_errno_win32;
767 // get next file, try unicode first
769 dp->valid_w = p_FindNextFileW(dp->dirh, &dp->data_w);
770 else if (p_FindNextFileA)
771 dp->valid_a = p_FindNextFileA(dp->dirh, &dp->data_a);
781 * Dotted IP address to network address
787 inet_aton(const char *a, struct in_addr *inp)
790 uint32_t acc = 0, tmp = 0;
793 if (!isdigit(*cp)) { /* first char must be digit */
794 return 0; /* error */
798 tmp = (tmp * 10) + (*cp -'0');
799 } else if (*cp == '.' || *cp == 0) {
801 return 0; /* error */
803 acc = (acc << 8) + tmp;
807 return 0; /* error */
809 } while (*cp++ != 0);
810 if (dotc != 4) { /* want 3 .'s plus EOS */
811 return 0; /* error */
813 inp->s_addr = htonl(acc); /* store addr in network format */
818 nanosleep(const struct timespec *req, struct timespec *rem)
821 rem->tv_sec = rem->tv_nsec = 0;
822 Sleep((req->tv_sec * 1000) + (req->tv_nsec/100000));
827 init_signals(void terminate(int sig))
833 init_stack_dump(void)
840 pathconf(const char *path, int name)
844 if (strncmp(path, "\\\\?\\", 4) == 0)
856 WORD wVersionRequested = MAKEWORD( 1, 1);
859 int err = WSAStartup(wVersionRequested, &wsaData);
863 printf("Can not start Windows Sockets\n");
873 win32_chdir(const char *dir)
875 if (p_SetCurrentDirectoryW) {
876 WCHAR szBuf[MAX_PATH_UNICODE];
877 UTF8_2_wchar(szBuf, dir, MAX_PATH_UNICODE);
879 if (0 == p_SetCurrentDirectoryW(szBuf)) {
880 errno = b_errno_win32;
884 else if (p_SetCurrentDirectoryA) {
885 if (0 == p_SetCurrentDirectoryA(dir)) {
886 errno = b_errno_win32;
896 win32_mkdir(const char *dir)
899 WCHAR szBuf[MAX_PATH_UNICODE];
900 UTF8_2_wchar(szBuf, dir, MAX_PATH_UNICODE);
901 return p_wmkdir(szBuf);
909 win32_getcwd(char *buf, int maxlen)
913 if (p_GetCurrentDirectoryW) {
914 WCHAR szBuf[MAX_PATH_UNICODE];
915 n = p_GetCurrentDirectoryW(maxlen, szBuf);
916 n = wchar_2_UTF8 (buf, szBuf, maxlen)-1;
917 } else if (p_GetCurrentDirectoryA)
918 n = p_GetCurrentDirectoryA(maxlen, buf);
920 if (n == 0 || n > maxlen) return NULL;
922 if (n+1 > maxlen) return NULL;
931 win32_fputs(const char *string, FILE *stream)
933 /* we use WriteConsoleA / WriteConsoleA
934 so we can be sure that unicode support works on win32.
935 with fallback if something fails
938 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
939 if (hOut && (hOut != INVALID_HANDLE_VALUE) && p_WideCharToMultiByte &&
940 p_MultiByteToWideChar && (stream == stdout)) {
942 WCHAR wszBuf[MAX_PATH_UNICODE];
943 char szBuf[MAX_PATH_UNICODE];
944 DWORD dwCharsWritten;
947 dwChars = UTF8_2_wchar(wszBuf, string, MAX_PATH_UNICODE);
949 /* try WriteConsoleW */
950 if (WriteConsoleW (hOut, wszBuf, dwChars-1, &dwCharsWritten, NULL))
951 return dwCharsWritten;
953 /* convert to local codepage and try WriteConsoleA */
954 dwChars = p_WideCharToMultiByte(GetConsoleOutputCP(),0,wszBuf,-1,szBuf,MAX_PATH_UNICODE,NULL,NULL);
955 if (WriteConsoleA (hOut, szBuf, dwChars-1, &dwCharsWritten, NULL))
956 return dwCharsWritten;
960 return fputs(string, stream);
964 win32_cgets (char* buffer, int len)
966 /* we use console ReadConsoleA / ReadConsoleW to be able to read unicode
967 from the win32 console and fallback if seomething fails */
969 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
970 if (hIn && (hIn != INVALID_HANDLE_VALUE) && p_WideCharToMultiByte && p_MultiByteToWideChar) {
975 /* nt and unicode conversion */
976 if (ReadConsoleW (hIn, wszBuf, 1024, &dwRead, NULL)) {
978 /* null terminate at end */
979 if (wszBuf[dwRead-1] == L'\n') {
980 wszBuf[dwRead-1] = L'\0';
984 if (wszBuf[dwRead-1] == L'\r') {
985 wszBuf[dwRead-1] = L'\0';
989 wchar_2_UTF8(buffer, wszBuf, len);
993 /* win 9x and unicode conversion */
994 if (ReadConsoleA (hIn, szBuf, 1024, &dwRead, NULL)) {
996 /* null terminate at end */
997 if (szBuf[dwRead-1] == L'\n') {
998 szBuf[dwRead-1] = L'\0';
1002 if (szBuf[dwRead-1] == L'\r') {
1003 szBuf[dwRead-1] = L'\0';
1007 /* convert from ansii to WCHAR */
1008 p_MultiByteToWideChar(GetConsoleCP(), 0, szBuf, -1, wszBuf,1024);
1009 /* convert from WCHAR to UTF-8 */
1010 if (wchar_2_UTF8(buffer, wszBuf, len))
1016 if (fgets(buffer, len, stdin))
1023 win32_unlink(const char *filename)
1027 WCHAR szBuf[MAX_PATH_UNICODE];
1028 UTF8_2_wchar(szBuf, filename, MAX_PATH_UNICODE);
1029 nRetCode = _wunlink(szBuf);
1031 nRetCode = _unlink(filename);
1037 #include "mswinver.h"
1039 char WIN_VERSION_LONG[64];
1040 char WIN_VERSION[32];
1047 static winver INIT; // cause constructor to be called before main()
1052 winver::winver(void)
1054 const char *version = "";
1055 const char *platform = "";
1056 OSVERSIONINFO osvinfo;
1057 osvinfo.dwOSVersionInfoSize = sizeof(osvinfo);
1059 // Get the current OS version
1060 if (!GetVersionEx(&osvinfo)) {
1061 version = "Unknown";
1062 platform = "Unknown";
1065 switch (_mkversion(osvinfo.dwPlatformId, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion))
1067 case MS_WINDOWS_95: (version = "Windows 95"); break;
1068 case MS_WINDOWS_98: (version = "Windows 98"); break;
1069 case MS_WINDOWS_ME: (version = "Windows ME"); break;
1070 case MS_WINDOWS_NT4:(version = "Windows NT 4.0"); platform = "NT"; break;
1071 case MS_WINDOWS_2K: (version = "Windows 2000");platform = "NT"; break;
1072 case MS_WINDOWS_XP: (version = "Windows XP");platform = "NT"; break;
1073 case MS_WINDOWS_S2003: (version = "Windows Server 2003");platform = "NT"; break;
1074 default: version = "Windows ??"; break;
1077 bstrncpy(WIN_VERSION_LONG, version, sizeof(WIN_VERSION_LONG));
1078 snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %d.%d.%d",
1079 platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
1082 HANDLE h = CreateFile("G:\\foobar", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
1086 BPIPE *b = open_bpipe("ls -l", 10, "r");
1088 while (!feof(b->rfd)) {
1089 fgets(buf, sizeof(buf), b->rfd);
1095 BOOL CreateChildProcess(VOID);
1096 VOID WriteToPipe(VOID);
1097 VOID ReadFromPipe(VOID);
1098 VOID ErrorExit(LPCSTR);
1099 VOID ErrMsg(LPTSTR, BOOL);
1102 * Check for a quoted path, if an absolute path name is given and it contains
1103 * spaces it will need to be quoted. i.e. "c:/Program Files/foo/bar.exe"
1104 * CreateProcess() says the best way to ensure proper results with executables
1105 * with spaces in path or filename is to quote the string.
1108 getArgv0(const char *cmdline)
1112 for (const char *cp = cmdline; *cp; cp++)
1117 if (!inquote && isspace(*cp))
1122 int len = cp - cmdline;
1123 char *rval = (char *)malloc(len+1);
1137 * OK, so it would seem CreateProcess only handles true executables:
1138 * .com or .exe files.
1139 * So test to see whether we're getting a .bat file and if so grab
1140 * $COMSPEC value and pass batch file to it.
1143 CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err)
1145 PROCESS_INFORMATION piProcInfo;
1146 STARTUPINFOA siStartInfo;
1147 BOOL bFuncRetn = FALSE;
1149 // Set up members of the PROCESS_INFORMATION structure.
1151 ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
1153 // Set up members of the STARTUPINFO structure.
1155 ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
1156 siStartInfo.cb = sizeof(STARTUPINFO);
1157 // setup new process to use supplied handles for stdin,stdout,stderr
1158 // if supplied handles are not used the send a copy of our STD_HANDLE
1160 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
1162 if (in != INVALID_HANDLE_VALUE)
1163 siStartInfo.hStdInput = in;
1165 siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1167 if (out != INVALID_HANDLE_VALUE)
1168 siStartInfo.hStdOutput = out;
1170 siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1171 if (err != INVALID_HANDLE_VALUE)
1172 siStartInfo.hStdError = err;
1174 siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1175 // Create the child process.
1179 const char *comspec = getenv("COMSPEC");
1181 if (comspec == NULL) // should never happen
1182 return INVALID_HANDLE_VALUE;
1184 char *cmdLine = (char *)alloca(strlen(cmdline) + strlen(comspec) + 16);
1186 strcpy(exeFile, comspec);
1187 strcpy(cmdLine, comspec);
1188 strcat(cmdLine, " /c ");
1189 strcat(cmdLine, cmdline);
1191 // try to execute program
1192 bFuncRetn = CreateProcessA(exeFile,
1193 cmdLine, // command line
1194 NULL, // process security attributes
1195 NULL, // primary thread security attributes
1196 TRUE, // handles are inherited
1197 0, // creation flags
1198 NULL, // use parent's environment
1199 NULL, // use parent's current directory
1200 &siStartInfo, // STARTUPINFO pointer
1201 &piProcInfo); // receives PROCESS_INFORMATION
1203 if (bFuncRetn == 0) {
1204 ErrorExit("CreateProcess failed\n");
1205 const char *err = errorString();
1206 d_msg(__FILE__, __LINE__, 99,
1207 "CreateProcess(%s, %s, ...)=%s\n", exeFile, cmdLine, err);
1208 LocalFree((void *)err);
1209 return INVALID_HANDLE_VALUE;
1211 // we don't need a handle on the process primary thread so we close
1213 CloseHandle(piProcInfo.hThread);
1215 return piProcInfo.hProcess;
1220 ErrorExit (LPCSTR lpszMessage)
1222 d_msg(__FILE__, __LINE__, 0, "%s", lpszMessage);
1227 typedef struct s_bpipe {
1229 time_t worker_stime;
1238 CloseIfValid(HANDLE handle)
1240 if (handle != INVALID_HANDLE_VALUE)
1241 CloseHandle(handle);
1246 open_bpipe(char *prog, int wait, const char *mode)
1248 HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
1249 hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup,
1252 SECURITY_ATTRIBUTES saAttr;
1256 hChildStdinRd = hChildStdinWr = hChildStdinWrDup =
1257 hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup =
1258 hInputFile = INVALID_HANDLE_VALUE;
1260 BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
1261 memset((void *)bpipe, 0, sizeof(BPIPE));
1263 int mode_read = (mode[0] == 'r');
1264 int mode_write = (mode[0] == 'w' || mode[1] == 'w');
1267 // Set the bInheritHandle flag so pipe handles are inherited.
1269 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1270 saAttr.bInheritHandle = TRUE;
1271 saAttr.lpSecurityDescriptor = NULL;
1275 // Create a pipe for the child process's STDOUT.
1276 if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
1277 ErrorExit("Stdout pipe creation failed\n");
1280 // Create noninheritable read handle and close the inheritable read
1283 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
1284 GetCurrentProcess(), &hChildStdoutRdDup , 0,
1286 DUPLICATE_SAME_ACCESS);
1288 ErrorExit("DuplicateHandle failed");
1292 CloseHandle(hChildStdoutRd);
1293 hChildStdoutRd = INVALID_HANDLE_VALUE;
1298 // Create a pipe for the child process's STDIN.
1300 if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
1301 ErrorExit("Stdin pipe creation failed\n");
1305 // Duplicate the write handle to the pipe so it is not inherited.
1306 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
1307 GetCurrentProcess(), &hChildStdinWrDup,
1309 FALSE, // not inherited
1310 DUPLICATE_SAME_ACCESS);
1312 ErrorExit("DuplicateHandle failed");
1316 CloseHandle(hChildStdinWr);
1317 hChildStdinWr = INVALID_HANDLE_VALUE;
1319 // spawn program with redirected handles as appropriate
1320 bpipe->worker_pid = (pid_t)
1321 CreateChildProcess(prog, // commandline
1322 hChildStdinRd, // stdin HANDLE
1323 hChildStdoutWr, // stdout HANDLE
1324 hChildStdoutWr); // stderr HANDLE
1326 if ((HANDLE) bpipe->worker_pid == INVALID_HANDLE_VALUE)
1330 bpipe->worker_stime = time(NULL);
1333 CloseHandle(hChildStdoutWr); // close our write side so when
1334 // process terminates we can
1336 // ugly but convert WIN32 HANDLE to FILE*
1337 int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
1339 bpipe->rfd = _fdopen(rfd, "r");
1343 CloseHandle(hChildStdinRd); // close our read side so as not
1344 // to interfre with child's copy
1345 // ugly but convert WIN32 HANDLE to FILE*
1346 int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
1348 bpipe->wfd = _fdopen(wfd, "w");
1353 bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
1360 CloseIfValid(hChildStdoutRd);
1361 CloseIfValid(hChildStdoutRdDup);
1362 CloseIfValid(hChildStdinWr);
1363 CloseIfValid(hChildStdinWrDup);
1365 free((void *) bpipe);
1366 errno = b_errno_win32; /* do GetLastError() for error code */
1373 kill(int pid, int signal)
1376 if (!TerminateProcess((HANDLE)pid, (UINT) signal)) {
1378 errno = b_errno_win32;
1380 CloseHandle((HANDLE)pid);
1387 close_bpipe(BPIPE *bpipe)
1390 int32_t remaining_wait = bpipe->wait;
1392 if (remaining_wait == 0) { /* wait indefinitely */
1393 remaining_wait = INT32_MAX;
1397 if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode)) {
1398 const char *err = errorString();
1399 rval = b_errno_win32;
1400 d_msg(__FILE__, __LINE__, 0,
1401 "GetExitCode error %s\n", err);
1402 LocalFree((void *)err);
1405 if (exitCode == STILL_ACTIVE) {
1406 if (remaining_wait <= 0) {
1407 rval = ETIME; /* timed out */
1410 bmicrosleep(1, 0); /* wait one second */
1412 } else if (exitCode != 0) {
1413 /* Truncate exit code as it doesn't seem to be correct */
1414 rval = (exitCode & 0xFF) | b_errno_exit;
1417 break; /* Shouldn't get here */
1421 if (bpipe->timer_id) {
1422 stop_child_timer(bpipe->timer_id);
1424 if (bpipe->rfd) fclose(bpipe->rfd);
1425 if (bpipe->wfd) fclose(bpipe->wfd);
1426 free((void *)bpipe);
1431 close_wpipe(BPIPE *bpipe)
1437 if (fclose(bpipe->wfd) != 0) {
1445 #include "findlib/find.h"
1448 utime(const char *fname, struct utimbuf *times)
1453 cygwin_conv_to_win32_path(fname, tmpbuf, 1024);
1455 cvt_utime_to_ftime(times->actime, acc);
1456 cvt_utime_to_ftime(times->modtime, mod);
1458 HANDLE h = INVALID_HANDLE_VALUE;
1460 if (p_CreateFileW) {
1461 WCHAR szBuf[MAX_PATH_UNICODE];
1462 UTF8_2_wchar(szBuf, tmpbuf, MAX_PATH_UNICODE);
1464 h = p_CreateFileW(szBuf,
1465 FILE_WRITE_ATTRIBUTES,
1471 } else if (p_CreateFileA) {
1472 h = p_CreateFileA(tmpbuf,
1473 FILE_WRITE_ATTRIBUTES,
1481 if (h == INVALID_HANDLE_VALUE) {
1482 const char *err = errorString();
1483 d_msg(__FILE__, __LINE__, 99,
1484 "Cannot open file \"%s\" for utime(): ERR=%s", tmpbuf, err);
1485 LocalFree((void *)err);
1486 errno = b_errno_win32;
1490 int rval = SetFileTime(h, NULL, &acc, &mod) ? 0 : -1;
1493 errno = b_errno_win32;
1498 #if USE_WIN32_COMPAT_IO
1501 open(const char *file, int flags, int mode)
1504 WCHAR szBuf[MAX_PATH_UNICODE];
1505 UTF8_2_wchar(szBuf, file, MAX_PATH_UNICODE);
1507 return p_wopen(szBuf, flags|_O_BINARY, mode);
1510 return _open(file, flags|_O_BINARY, mode);
1514 * Note, this works only for a file. If you want
1515 * to close a socket, use closesocket().
1516 * Bacula has been modified in src/lib/bnet.c
1517 * to use closesocket().
1525 #ifndef HAVE_WXCONSOLE
1527 read(int fd, void *buf, ssize_t len)
1529 return _read(fd, buf, (size_t)len);
1533 write(int fd, const void *buf, ssize_t len)
1535 return _write(fd, buf, (size_t)len);
1541 lseek(int fd, off_t offset, int whence)
1543 return _lseeki64(fd, offset, whence);
1547 dup2(int fd1, int fd2)
1549 return _dup2(fd1, fd2);
1553 open(const char *file, int flags, int mode)
1556 DWORD shareMode = 0;
1559 HANDLE foo = INVALID_HANDLE_VALUE;
1560 const char *remap = file;
1562 if (flags & O_WRONLY) access = GENERIC_WRITE;
1563 else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
1564 else access = GENERIC_READ;
1566 if (flags & O_CREAT) create = CREATE_NEW;
1567 else create = OPEN_EXISTING;
1569 if (flags & O_TRUNC) create = TRUNCATE_EXISTING;
1571 if (!(flags & O_EXCL))
1572 shareMode = FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE;
1574 if (flags & O_APPEND) {
1575 printf("open...APPEND not implemented yet.");
1579 if (p_CreateFileW) {
1580 WCHAR szBuf[MAX_PATH_UNICODE];
1581 UTF8_2_wchar(szBuf, file, MAX_PATH_UNICODE);
1583 foo = p_CreateFileW(szBuf, access, shareMode, NULL, create, msflags, NULL);
1585 else if (p_CreateFileA)
1586 foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
1588 if (INVALID_HANDLE_VALUE == foo) {
1589 errno = b_errno_win32;
1600 if (!CloseHandle((HANDLE)fd)) {
1601 errno = b_errno_win32;
1609 write(int fd, const void *data, ssize_t len)
1613 status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
1614 if (status) return bwrite;
1615 errno = b_errno_win32;
1621 read(int fd, void *data, ssize_t len)
1626 status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
1627 if (status) return bread;
1628 errno = b_errno_win32;
1633 lseek(int fd, off_t offset, int whence)
1639 method = FILE_BEGIN;
1642 method = FILE_CURRENT;
1652 if ((val=SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method)) == INVALID_SET_FILE_POINTER) {
1653 errno = b_errno_win32;
1656 /* ***FIXME*** I doubt this works right */
1673 /* syslog function, added by Nicolas Boichat */