2 // compat.cpp -- compatibilty layer to make bacula-fd run
3 // natively under windows
5 // Copyright (C)2004 Raider Solutions, Inc
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of
10 // the License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public
18 // License along with this program; if not, write to the Free
19 // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20 // MA 02111-1307, USA.
22 // Author : Christopher S. Hull
23 // Created On : Sat Jan 31 15:55:00 2004
24 // Last Modified By: Christopher S. Hull
25 // Last Modified On: Wed Feb 18 09:12:15 2004
34 extern void d_msg(const char *file, int line, int level, const char *fmt,...);
35 extern DWORD g_platform_id;
39 cygwin_conv_to_win32_path(const char *name, char *win32_name)
45 *win32_name++ = *name;
48 if (win32_name[-1] == '\\')
56 open(const char *file, int flags, int mode)
63 const char *remap = file;
65 if (flags & O_WRONLY) access = GENERIC_WRITE;
66 else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
67 else access = GENERIC_READ;
69 if (flags & O_CREAT) create = CREATE_NEW;
70 else create = OPEN_EXISTING;
72 if (flags & O_TRUNC) create = TRUNCATE_EXISTING;
74 if (!(flags & O_EXCL))
75 shareMode = FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE;
79 printf("open...APPEND not implemented yet.");
83 foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
84 if (INVALID_HANDLE_VALUE == foo)
95 if (!CloseHandle((HANDLE)fd))
102 write(int fd, const void *data, int32_t len)
106 status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
107 if (status) return bwrite;
113 read(int fd, void *data, int32_t len)
118 status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
119 if (status) return bread;
131 chmod(const char *, mode_t)
137 chown(const char *k, uid_t, gid_t)
143 lchown(const char *k, uid_t, gid_t)
149 utime(const char *, struct utimbuf *)
162 srandom(unsigned int seed)
166 // /////////////////////////////////////////////////////////////////
167 // convert from Windows concept of time to Unix concept of time
168 // /////////////////////////////////////////////////////////////////
170 cvt(const FILETIME &time)
172 uint64_t mstime = time.dwHighDateTime;
174 mstime |= time.dwLowDateTime;
176 mstime /= 10000000; // convert to seconds.
177 mstime -= 3234336I64*3600I64; // difference between jan 1, 1601
180 return (time_t) (mstime & 0xffffffff);
188 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
189 FORMAT_MESSAGE_FROM_SYSTEM |
190 FORMAT_MESSAGE_IGNORE_INSERTS,
193 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default lang
198 return (const char *) lpMsgBuf;
202 statDir(const char *file, struct stat *sb)
204 WIN32_FIND_DATA info; // window's file info
205 sb->st_mode |= S_IFDIR;
207 if (file[1] == ':' && file[2] == 0)
209 d_msg(__FILE__, __LINE__, 99, "faking ROOT attrs(%s).\n", file);
210 sb->st_mode |= S_IREAD|S_IEXEC|S_IWRITE;
216 HANDLE h = FindFirstFile(file, &info);
218 if (h == INVALID_HANDLE_VALUE) {
219 const char *err = errorString();
220 d_msg(__FILE__, __LINE__, 99, "FindFirstFile(%s):%s\n", file, err);
221 LocalFree((void *)err);
222 errno = GetLastError();
226 sb->st_mode |= (S_IREAD | S_IEXEC);
227 if (!(info.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
228 sb->st_mode |= S_IWRITE;
230 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
231 sb->st_mode |= S_IRGRP;
232 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
233 sb->st_mode |= S_IROTH;
234 sb->st_size = info.nFileSizeHigh;
236 sb->st_size |= info.nFileSizeLow;
237 sb->st_blksize = 4096;
238 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
239 sb->st_atime = cvt(info.ftLastAccessTime);
240 sb->st_mtime = cvt(info.ftLastWriteTime);
241 sb->st_ctime = cvt(info.ftCreationTime);
247 stat2(const char *file, struct stat *sb)
249 BY_HANDLE_FILE_INFORMATION info;
253 cygwin_conv_to_win32_path(file, tmpbuf);
255 DWORD attr = GetFileAttributes(tmpbuf);
258 const char *err = errorString();
259 d_msg(__FILE__, __LINE__, 99,
260 "GetFileAttrubtes(%s): %s\n", tmpbuf, err);
261 LocalFree((void *)err);
262 errno = GetLastError();
266 if (attr & FILE_ATTRIBUTE_DIRECTORY)
267 return statDir(tmpbuf, sb);
269 sb->st_mode |= S_IFREG;
271 h = CreateFile(tmpbuf, GENERIC_READ,
272 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
274 if (h == INVALID_HANDLE_VALUE) {
275 const char *err = errorString();
276 d_msg(__FILE__, __LINE__, 99,
277 "Cannot open file for stat (%s):%s\n", tmpbuf, err);
278 LocalFree((void *)err);
280 errno = GetLastError();
284 if (!GetFileInformationByHandle(h, &info)) {
285 const char *err = errorString();
286 d_msg(__FILE__, __LINE__, 99,
287 "GetfileInformationByHandle(%s): %s\n", tmpbuf, err);
288 LocalFree((void *)err);
290 errno = GetLastError();
294 sb->st_dev = info.dwVolumeSerialNumber;
295 sb->st_ino = info.nFileIndexHigh;
297 sb->st_ino |= info.nFileIndexLow;
298 sb->st_nlink = (short)info.nNumberOfLinks;
299 sb->st_mode |= (S_IREAD | S_IEXEC);
300 if (!(info.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
301 sb->st_mode |= S_IWRITE;
303 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
304 sb->st_mode |= S_IRGRP;
305 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
306 sb->st_mode |= S_IROTH;
307 sb->st_size = info.nFileSizeHigh;
309 sb->st_size |= info.nFileSizeLow;
310 sb->st_blksize = 4096;
311 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
312 sb->st_atime = cvt(info.ftLastAccessTime);
313 sb->st_mtime = cvt(info.ftLastWriteTime);
314 sb->st_ctime = cvt(info.ftCreationTime);
322 stat(const char *file, struct stat *sb)
324 WIN32_FILE_ATTRIBUTE_DATA data;
327 memset(sb, 0, sizeof(*sb));
329 if (g_platform_id == VER_PLATFORM_WIN32_WINDOWS)
330 return stat2(file, sb);
332 if (!GetFileAttributesEx(file, GetFileExInfoStandard, &data))
333 return stat2(file, sb);
335 if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
336 sb->st_mode |= S_IFDIR;
338 sb->st_mode |= S_IFREG;
341 sb->st_mode |= (S_IREAD | S_IEXEC);
342 if (!(data.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
343 sb->st_mode |= S_IWRITE;
345 if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
346 sb->st_mode |= S_IRGRP;
347 if (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
348 sb->st_mode |= S_IROTH;
349 sb->st_size = data.nFileSizeHigh;
351 sb->st_size |= data.nFileSizeLow;
352 sb->st_blksize = 4096;
353 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
354 sb->st_atime = cvt(data.ftLastAccessTime);
355 sb->st_mtime = cvt(data.ftLastWriteTime);
356 sb->st_ctime = cvt(data.ftCreationTime);
361 lstat(const char *file, struct stat *sb)
363 return stat(file, sb);
379 execvp(const char *, char *[]) {
402 waitpid(int, int*, int)
408 readlink(const char *, char *, int)
414 lseek(int fd, int offset, int whence)
422 method = FILE_CURRENT;
431 return SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method);
435 strcasecmp(const char *s1, const char *s2)
437 register int ch1, ch2;
440 return 0; /* strings are equal if same object. */
451 } while (ch1 != 0 && tolower(ch1) == tolower(ch2));
457 strncasecmp(const char *s1, const char *s2, int len)
459 register int ch1, ch2;
462 return 0; /* strings are equal if same object. */
473 } while (len-- && ch1 != 0 && tolower(ch1) == tolower(ch2));
479 gettimeofday(struct timeval *tv, struct timezone *)
485 if (tv == NULL) return -1;
486 if (!SystemTimeToFileTime(&now, &tmp)) return -1;
488 int64_t _100nsec = tmp.dwHighDateTime;
490 _100nsec |= tmp.dwLowDateTime;
491 _100nsec -= (3234336I64*3600I64 * 10000000I64);
492 tv->tv_sec =(long) (_100nsec / 10000000);
493 tv->tv_usec = (long) ((_100nsec % 10000000)/10);
499 syslog(int, const char *, const char *)
517 // implement opendir/readdir/closedir on top of window's API
520 WIN32_FIND_DATA data; // window's file info
521 const char *spec; // the directory we're traversing
522 HANDLE dirh; // the search handle
523 BOOL valid; // the info in data field is valid
524 UINT32 offset; // pseudo offset for d_off
528 opendir(const char *path)
531 if (path == NULL) return NULL;
533 rval = (_dir *)malloc(sizeof(_dir));
534 if (rval == NULL) return NULL;
535 char *tspec = (char *)malloc(strlen(path)+16);
536 if (tspec == NULL) goto err1;
538 if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS) {
539 // allow path to be 32767 bytes
545 cygwin_conv_to_win32_path(path, tspec+4);
548 cygwin_conv_to_win32_path(path, tspec);
550 strcat(tspec, "\\*");
553 rval->dirh = FindFirstFile(rval->spec, &rval->data);
554 d_msg(__FILE__, __LINE__,
555 99, "opendir(%s)\n\tspec=%s,\n\tFindFirstFile returns %d\n",
556 path, rval->spec, rval->dirh);
559 if (rval->dirh == INVALID_HANDLE_VALUE)
562 d_msg(__FILE__, __LINE__,
563 99, "\tFirstFile=%s\n", rval->data.cFileName);
566 free((void *)rval->spec);
575 _dir *dp = (_dir *)dirp;
577 free((void *)dp->spec);
583 typedef struct _WIN32_FIND_DATA {
584 DWORD dwFileAttributes;
585 FILETIME ftCreationTime;
586 FILETIME ftLastAccessTime;
587 FILETIME ftLastWriteTime;
592 TCHAR cFileName[MAX_PATH];
593 TCHAR cAlternateFileName[14];
594 } WIN32_FIND_DATA, *PWIN32_FIND_DATA;
598 copyin(struct dirent &dp, const char *fname)
602 char *cp = dp.d_name;
611 readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
614 _dir *dp = (_dir *)dirp;
616 entry->d_off = dp->offset;
617 dp->offset += copyin(*entry, dp->data.cFileName);
618 d_msg(__FILE__, __LINE__,
619 99, "readdir_r(%p, { d_name=\"%s\", d_reclen=%d, d_off=%d\n",
620 dirp, entry->d_name, entry->d_reclen, entry->d_off);
624 dp->valid = FindNextFile(dp->dirh, &dp->data);
630 inet_aton(const char *a, struct in_addr *inp)
634 uint32_t acc = 0, tmp = 0;
636 if (!isdigit(*a)) return 0;
639 tmp = (tmp * 10) + (*cp -'0');
640 else if (*cp == '.') {
641 if (tmp > 255) return 0;
642 acc = (acc << 8) + tmp;
648 if (dotc != 3) return 0;
654 nanosleep(const struct timespec *req, struct timespec *rem)
657 rem->tv_sec = rem->tv_nsec = 0;
658 Sleep((req->tv_sec * 1000) + (req->tv_nsec/100000));
663 init_signals(void terminate(int sig))
669 init_stack_dump(void)
676 pathconf(const char *path, int name)
680 if (strncmp(path, "\\\\?\\", 4) == 0)
692 WORD wVersionRequested = MAKEWORD( 1, 1);
695 int err = WSAStartup(wVersionRequested, &wsaData);
700 printf("Can not start Windows Sockets\n");
709 win32_chdir(const char *dir)
711 if (0 == SetCurrentDirectory(dir)) return -1;
716 win32_getcwd(char *buf, int maxlen)
718 int n = GetCurrentDirectory(maxlen, buf);
720 if (n == 0 || n > maxlen) return NULL;
722 if (n+1 > maxlen) return NULL;
731 #include "mswinver.h"
733 char WIN_VERSION_LONG[64];
734 char WIN_VERSION[32];
741 static winver INIT; // cause constructor to be called before main()
748 const char *version = "";
749 const char *platform = "";
750 OSVERSIONINFO osvinfo;
751 osvinfo.dwOSVersionInfoSize = sizeof(osvinfo);
753 // Get the current OS version
754 if (!GetVersionEx(&osvinfo)) {
756 platform = "Unknown";
759 switch (_mkversion(osvinfo.dwPlatformId, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion))
761 case MS_WINDOWS_95: (version = "Windows 95"); break;
762 case MS_WINDOWS_98: (version = "Windows 98"); break;
763 case MS_WINDOWS_ME: (version = "Windows ME"); break;
764 case MS_WINDOWS_NT4:(version = "Windows NT 4.0"); platform = "NT"; break;
765 case MS_WINDOWS_2K: (version = "Windows 2000");platform = "NT"; break;
766 case MS_WINDOWS_XP: (version = "Windows XP");platform = "NT"; break;
767 case MS_WINDOWS_S2003: (version = "Windows Server 2003");platform = "NT"; break;
768 default: version = "Windows ??"; break;
771 strcpy(WIN_VERSION_LONG, version);
772 snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %d.%d.%d",
773 platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
776 BPIPE *b = open_bpipe("ls -l", 10, "r");
778 while (!feof(b->rfd)) {
779 fgets(buf, sizeof(buf), b->rfd);
786 BOOL CreateChildProcess(VOID);
787 VOID WriteToPipe(VOID);
788 VOID ReadFromPipe(VOID);
789 VOID ErrorExit(LPTSTR);
790 VOID ErrMsg(LPTSTR, BOOL);
794 getArgv0(const char *cmdline)
796 const char *cp = cmdline;
798 while (*cp && !isspace(*cp)) cp++;
800 int len = cp - cmdline;
801 char *rval = (char *)malloc(len+1);
813 CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err)
815 PROCESS_INFORMATION piProcInfo;
816 STARTUPINFO siStartInfo;
817 BOOL bFuncRetn = FALSE;
819 // Set up members of the PROCESS_INFORMATION structure.
821 ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
823 // Set up members of the STARTUPINFO structure.
825 ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
826 siStartInfo.cb = sizeof(STARTUPINFO);
827 // setup new process to use supplied handles for stdin,stdout,stderr
828 // if supplied handles are not used the send a copy of our STD_HANDLE
830 siStartInfo.dwFlags = STARTF_USESTDHANDLES;
832 if (in != INVALID_HANDLE_VALUE)
833 siStartInfo.hStdInput = in;
835 siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
837 if (out != INVALID_HANDLE_VALUE)
838 siStartInfo.hStdOutput = out;
840 siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
841 if (err != INVALID_HANDLE_VALUE)
842 siStartInfo.hStdError = err;
844 siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
845 // Create the child process.
849 // retrive the first compont of the command line which should be the
851 const char *exeName = getArgv0(cmdline);
852 // check to see if absolute path was passed to us already?
853 if (exeName[1] != ':'
854 || (strchr(cmdline, '/') == NULL
855 && strchr(cmdline, '\\') == NULL))
857 // only command name so perform search of PATH to find
859 DWORD rval = SearchPath(NULL,
866 return INVALID_HANDLE_VALUE;
867 if (rval > sizeof(exeFile))
868 return INVALID_HANDLE_VALUE;
872 strcpy(exeFile, exeName);
874 // exeFile now has absolute path to program to execute.
875 free((void *)exeName);
876 // copy original command line to pass to create process
877 strcpy(cmdLine, cmdline);
878 // try to execute program
879 bFuncRetn = CreateProcess(exeFile,
880 cmdLine, // command line
881 NULL, // process security attributes
882 NULL, // primary thread security attributes
883 TRUE, // handles are inherited
885 NULL, // use parent's environment
886 NULL, // use parent's current directory
887 &siStartInfo, // STARTUPINFO pointer
888 &piProcInfo); // receives PROCESS_INFORMATION
890 if (bFuncRetn == 0) {
891 ErrorExit("CreateProcess failed\n");
892 return INVALID_HANDLE_VALUE;
894 // we don't need a handle on the process primary thread so we close
896 CloseHandle(piProcInfo.hThread);
898 return piProcInfo.hProcess;
903 ErrorExit (LPTSTR lpszMessage)
905 d_msg(__FILE__, __LINE__, 0, "%s", lpszMessage);
910 typedef struct s_bpipe {
921 CloseIfValid(HANDLE handle)
923 if (handle != INVALID_HANDLE_VALUE)
926 // include <io.h> causes to many conflicts with some of
927 // the fuctions we define here.
929 int __cdecl _open_osfhandle(long, int);
933 open_bpipe(char *prog, int wait, const char *mode)
935 HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
936 hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup,
939 SECURITY_ATTRIBUTES saAttr;
943 hChildStdinRd = hChildStdinWr = hChildStdinWrDup =
944 hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup =
945 hInputFile = INVALID_HANDLE_VALUE;
947 BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
948 memset((void *)bpipe, 0, sizeof(BPIPE));
950 int mode_read = (mode[0] == 'r');
951 int mode_write = (mode[0] == 'w' || mode[1] == 'w');
954 // Set the bInheritHandle flag so pipe handles are inherited.
956 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
957 saAttr.bInheritHandle = TRUE;
958 saAttr.lpSecurityDescriptor = NULL;
962 // Create a pipe for the child process's STDOUT.
963 if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
964 ErrorExit("Stdout pipe creation failed\n");
967 // Create noninheritable read handle and close the inheritable read
970 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
971 GetCurrentProcess(), &hChildStdoutRdDup , 0,
973 DUPLICATE_SAME_ACCESS);
975 ErrorExit("DuplicateHandle failed");
979 CloseHandle(hChildStdoutRd);
984 // Create a pipe for the child process's STDIN.
986 if (! CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
987 ErrorExit("Stdin pipe creation failed\n");
991 // Duplicate the write handle to the pipe so it is not inherited.
992 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
993 GetCurrentProcess(), &hChildStdinWrDup,
995 FALSE, // not inherited
996 DUPLICATE_SAME_ACCESS);
998 ErrorExit("DuplicateHandle failed");
1002 CloseHandle(hChildStdinWr);
1004 // spawn program with redirected handles as appropriate
1005 bpipe->worker_pid = (pid_t)
1006 CreateChildProcess(prog, // commandline
1007 hChildStdinRd, // stdin HANDLE
1008 hChildStdoutWr, // stdout HANDLE
1009 hChildStdoutWr);// stderr HANDLE
1011 if ((HANDLE) bpipe->worker_pid == INVALID_HANDLE_VALUE)
1015 bpipe->worker_stime = time(NULL);
1018 CloseHandle(hChildStdoutWr); // close our write side so when
1019 // process terminates we can
1021 // ugly but convert WIN32 HANDLE to FILE*
1022 int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
1023 bpipe->rfd = _fdopen(rfd, "r");
1026 CloseHandle(hChildStdinRd); // close our read side so as not
1027 // to interfre with child's copy
1028 // ugly but convert WIN32 HANDLE to FILE*
1029 int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
1030 bpipe->wfd = _fdopen(wfd, "w");
1034 bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
1041 CloseIfValid(hChildStdoutRd);
1042 CloseIfValid(hChildStdoutRdDup);
1043 CloseIfValid(hChildStdinWr);
1044 CloseIfValid(hChildStdinWrDup);
1046 free((void *) bpipe);
1052 kill(int pid, int signal)
1055 if (!TerminateProcess((HANDLE)pid, (UINT) signal))
1057 CloseHandle((HANDLE)pid);
1062 close_bpipe(BPIPE *bpipe)
1065 if (bpipe->rfd) fclose(bpipe->rfd);
1066 if (bpipe->wfd) fclose(bpipe->wfd);
1069 int remaining_wait = bpipe->wait;
1073 if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode))
1075 const char *err = errorString();
1076 rval = GetLastError();
1077 d_msg(__FILE__, __LINE__, 0,
1078 "GetExitCode error %s\n", err);
1079 LocalFree((void *)err);
1083 if (exitCode == STILL_ACTIVE) {
1084 bmicrosleep(1, 0); /* wait one second */
1088 } while(remaining_wait);
1091 if (bpipe->timer_id) {
1092 stop_child_timer(bpipe->timer_id);
1094 free((void *)bpipe);
1099 close_wpipe(BPIPE *bpipe)
1105 if (fclose(bpipe->wfd) != 0) {