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: Mon Feb 9 12:18:04 2004
34 extern void d_msg(char *file, int line, int level, 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 and jan, 1 1970
179 return (time_t) (mstime & 0xffffffff);
187 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
188 FORMAT_MESSAGE_FROM_SYSTEM |
189 FORMAT_MESSAGE_IGNORE_INSERTS,
192 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default lang
197 return (const char *) lpMsgBuf;
201 statDir(const char *file, struct stat *sb)
203 WIN32_FIND_DATA info; // window's file info
204 sb->st_mode |= S_IFDIR;
206 if (file[1] == ':' && file[2] == 0)
208 d_msg(__FILE__, __LINE__, 99, "faking ROOT attrs(%s).\n", file);
209 sb->st_mode |= S_IREAD|S_IEXEC|S_IWRITE;
215 HANDLE h = FindFirstFile(file, &info);
217 if (h == INVALID_HANDLE_VALUE) {
218 const char *err = errorString();
219 d_msg(__FILE__, __LINE__, 99, "FindFirstFile(%s):%s\n", file, err);
220 LocalFree((void *)err);
221 errno = GetLastError();
225 sb->st_mode |= (S_IREAD | S_IEXEC);
226 if (!(info.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
227 sb->st_mode |= S_IWRITE;
229 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
230 sb->st_mode |= S_IRGRP;
231 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
232 sb->st_mode |= S_IROTH;
233 sb->st_size = info.nFileSizeHigh;
235 sb->st_size |= info.nFileSizeLow;
236 sb->st_blksize = 4096;
237 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
238 sb->st_atime = cvt(info.ftLastAccessTime);
239 sb->st_mtime = cvt(info.ftLastWriteTime);
240 sb->st_ctime = cvt(info.ftCreationTime);
246 stat2(const char *file, struct stat *sb)
248 BY_HANDLE_FILE_INFORMATION info;
252 cygwin_conv_to_win32_path(file, tmpbuf);
254 DWORD attr = GetFileAttributes(tmpbuf);
257 const char *err = errorString();
258 d_msg(__FILE__, __LINE__, 99, "GetFileAttrubtes(%s): %s\n", tmpbuf, err);
259 LocalFree((void *)err);
260 errno = GetLastError();
264 if (attr & FILE_ATTRIBUTE_DIRECTORY)
265 return statDir(tmpbuf, sb);
267 sb->st_mode |= S_IFREG;
269 h = CreateFile(tmpbuf, GENERIC_READ,
270 FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
272 if (h == INVALID_HANDLE_VALUE) {
273 const char *err = errorString();
274 d_msg(__FILE__, __LINE__, 99, "Cannot open file for stat (%s):%s\n", tmpbuf, err);
275 LocalFree((void *)err);
277 errno = GetLastError();
281 if (!GetFileInformationByHandle(h, &info)) {
282 const char *err = errorString();
283 d_msg(__FILE__, __LINE__, 99, "GetfileInformationByHandle(%s): %s\n", tmpbuf, err);
284 LocalFree((void *)err);
286 errno = GetLastError();
290 sb->st_dev = info.dwVolumeSerialNumber;
291 sb->st_ino = info.nFileIndexHigh;
293 sb->st_ino |= info.nFileIndexLow;
294 sb->st_nlink = (short)info.nNumberOfLinks;
295 sb->st_mode |= (S_IREAD | S_IEXEC);
296 if (!(info.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
297 sb->st_mode |= S_IWRITE;
299 if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
300 sb->st_mode |= S_IRGRP;
301 if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
302 sb->st_mode |= S_IROTH;
303 sb->st_size = info.nFileSizeHigh;
305 sb->st_size |= info.nFileSizeLow;
306 sb->st_blksize = 4096;
307 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
308 sb->st_atime = cvt(info.ftLastAccessTime);
309 sb->st_mtime = cvt(info.ftLastWriteTime);
310 sb->st_ctime = cvt(info.ftCreationTime);
317 stat(const char *file, struct stat *sb)
319 WIN32_FILE_ATTRIBUTE_DATA data;
322 memset(sb, 0, sizeof(*sb));
324 if (g_platform_id == VER_PLATFORM_WIN32_WINDOWS)
325 return stat2(file, sb);
327 if (!GetFileAttributesEx(file, GetFileExInfoStandard, &data))
328 return stat2(file, sb);
330 if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
331 sb->st_mode |= S_IFDIR;
333 sb->st_mode |= S_IFREG;
336 sb->st_mode |= (S_IREAD | S_IEXEC);
337 if (!(data.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
338 sb->st_mode |= S_IWRITE;
340 if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
341 sb->st_mode |= S_IRGRP;
342 if (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
343 sb->st_mode |= S_IROTH;
344 sb->st_size = data.nFileSizeHigh;
346 sb->st_size |= data.nFileSizeLow;
347 sb->st_blksize = 4096;
348 sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
349 sb->st_atime = cvt(data.ftLastAccessTime);
350 sb->st_mtime = cvt(data.ftLastWriteTime);
351 sb->st_ctime = cvt(data.ftCreationTime);
356 lstat(const char *file, struct stat *sb)
358 return stat(file, sb);
373 execvp(const char *, char *[]) {
396 waitpid(int, int*, int)
402 readlink(const char *, char *, int)
408 lseek(int fd, int offset, int whence)
416 method = FILE_CURRENT;
425 return SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method);
429 strcasecmp(const char *s1, const char *s2)
431 register int ch1, ch2;
434 return 0; /* strings are equal if same object. */
445 } while (ch1 != 0 && tolower(ch1) == tolower(ch2));
451 strncasecmp(const char *s1, const char *s2, int len)
453 register int ch1, ch2;
456 return 0; /* strings are equal if same object. */
467 } while (len-- && ch1 != 0 && tolower(ch1) == tolower(ch2));
473 gettimeofday(struct timeval *tv, struct timezone *)
479 if (tv == NULL) return -1;
480 if (!SystemTimeToFileTime(&now, &tmp)) return -1;
482 int64_t _100nsec = tmp.dwHighDateTime;
484 _100nsec |= tmp.dwLowDateTime;
485 _100nsec -= (3234336I64*3600I64 * 10000000I64);
486 tv->tv_sec =(long) (_100nsec / 10000000);
487 tv->tv_usec = (long) ((_100nsec % 10000000)/10);
493 syslog(int, const char *, const char *)
510 // implement opendir/readdir/closedir on top of window's API
513 WIN32_FIND_DATA data; // window's file info
514 const char *spec; // the directory we're traversing
515 HANDLE dirh; // the search handle
516 BOOL valid; // the info in data field is valid
517 UINT32 offset; // pseudo offset for d_off
521 opendir(const char *path)
524 if (path == NULL) return NULL;
526 rval = (_dir *)malloc(sizeof(_dir));
527 if (rval == NULL) return NULL;
528 char *tspec = (char *)malloc(strlen(path)+16);
529 if (tspec == NULL) goto err1;
531 if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS) {
532 // allow path to be 32767 bytes
538 cygwin_conv_to_win32_path(path, tspec+4);
541 cygwin_conv_to_win32_path(path, tspec);
543 strcat(tspec, "\\*");
546 rval->dirh = FindFirstFile(rval->spec, &rval->data);
547 d_msg(__FILE__, __LINE__,
548 99, "opendir(%s)\n\tspec=%s,\n\tFindFirstFile returns %d\n",
549 path, rval->spec, rval->dirh);
552 if (rval->dirh == INVALID_HANDLE_VALUE)
555 d_msg(__FILE__, __LINE__,
556 99, "\tFirstFile=%s\n", rval->data.cFileName);
559 free((void *)rval->spec);
568 _dir *dp = (_dir *)dirp;
570 free((void *)dp->spec);
576 typedef struct _WIN32_FIND_DATA {
577 DWORD dwFileAttributes;
578 FILETIME ftCreationTime;
579 FILETIME ftLastAccessTime;
580 FILETIME ftLastWriteTime;
585 TCHAR cFileName[MAX_PATH];
586 TCHAR cAlternateFileName[14];
587 } WIN32_FIND_DATA, *PWIN32_FIND_DATA;
591 copyin(struct dirent &dp, const char *fname)
595 char *cp = dp.d_name;
604 readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
607 _dir *dp = (_dir *)dirp;
609 entry->d_off = dp->offset;
610 dp->offset += copyin(*entry, dp->data.cFileName);
611 d_msg(__FILE__, __LINE__,
612 99, "readdir_r(%p, { d_name=\"%s\", d_reclen=%d, d_off=%d\n",
613 dirp, entry->d_name, entry->d_reclen, entry->d_off);
617 dp->valid = FindNextFile(dp->dirh, &dp->data);
623 inet_aton(const char *a, struct in_addr *inp)
627 uint32_t acc = 0, tmp = 0;
629 if (!isdigit(*a)) return 0;
632 tmp = (tmp * 10) + (*cp -'0');
633 else if (*cp == '.') {
634 if (tmp > 255) return 0;
635 acc = (acc << 8) + tmp;
641 if (dotc != 3) return 0;
647 nanosleep(const struct timespec *req, struct timespec *rem)
650 rem->tv_sec = rem->tv_nsec = 0;
651 Sleep((req->tv_sec * 1000) + (req->tv_nsec/100000));
656 init_signals(void terminate(int sig))
662 init_stack_dump(void)
669 pathconf(const char *path, int name)
673 if (strncmp(path, "\\\\?\\", 4) == 0)
685 WORD wVersionRequested = MAKEWORD( 1, 1);
688 int err = WSAStartup(wVersionRequested, &wsaData);
693 printf("Can not start Windows Sockets\n");
702 win32_chdir(const char *dir)
704 if (0 == SetCurrentDirectory(dir)) return -1;
709 win32_getcwd(char *buf, int maxlen)
711 int n = GetCurrentDirectory(maxlen, buf);
713 if (n == 0 || n > maxlen) return NULL;
715 if (n+1 > maxlen) return NULL;
724 #include "mswinver.h"
726 char WIN_VERSION_LONG[64];
727 char WIN_VERSION[32];
734 static winver INIT; // cause constructor to be called before main()
738 const char *version = "";
739 const char *platform = "";
740 OSVERSIONINFO osvinfo;
741 osvinfo.dwOSVersionInfoSize = sizeof(osvinfo);
743 // Get the current OS version
744 if (!GetVersionEx(&osvinfo)) {
746 platform = "Unknown";
749 switch (_mkversion(osvinfo.dwPlatformId, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion))
751 case MS_WINDOWS_95: (version = "Windows 95"); break;
752 case MS_WINDOWS_98: (version = "Windows 98"); break;
753 case MS_WINDOWS_ME: (version = "Windows ME"); break;
754 case MS_WINDOWS_NT4:(version = "Windows NT 4.0"); platform = "NT"; break;
755 case MS_WINDOWS_2K: (version = "Windows 2000");platform = "NT"; break;
756 case MS_WINDOWS_XP: (version = "Windows XP");platform = "NT"; break;
757 case MS_WINDOWS_S2003: (version = "Windows Server 2003");platform = "NT"; break;
760 strcpy(WIN_VERSION_LONG, version);
761 snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %d.%d.%d",
762 platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
772 HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
773 hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup,
774 hInputFile, hSaveStdin, hSaveStdout;
776 BOOL CreateChildProcess(VOID);
777 VOID WriteToPipe(VOID);
778 VOID ReadFromPipe(VOID);
779 VOID ErrorExit(LPTSTR);
780 VOID ErrMsg(LPTSTR, BOOL);
783 const char *getArgv0(const char *cmdline)
785 const char *cp = cmdline;
787 while (*cp && !isspace(*cp)) cp++;
789 int len = cp - cmdline;
790 char *rval = (char *)malloc(len+1);
801 CreateChildProcess(const char *cmdline)
803 PROCESS_INFORMATION piProcInfo;
804 STARTUPINFO siStartInfo;
805 BOOL bFuncRetn = FALSE;
807 // Set up members of the PROCESS_INFORMATION structure.
809 ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
811 // Set up members of the STARTUPINFO structure.
813 ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
814 siStartInfo.cb = sizeof(STARTUPINFO);
816 // Create the child process.
818 const char *exeName = getArgv0(cmdline);
819 if (exeName[1] != ':'
820 || (strchr(cmdline, '/') == NULL
821 && strchr(cmdline, '\\') == NULL))
825 DWORD rval = SearchPath(NULL,
832 return INVALID_HANDLE_VALUE;
833 if (rval > sizeof(buf))
834 return INVALID_HANDLE_VALUE;
835 free((void *)exeName);
836 exeName = strdup(buf);
839 char *cmdLine = strdup(cmdline);
841 bFuncRetn = CreateProcess(exeName,
842 cmdLine, // command line
843 NULL, // process security attributes
844 NULL, // primary thread security attributes
845 TRUE, // handles are inherited
847 NULL, // use parent's environment
848 NULL, // use parent's current directory
849 &siStartInfo, // STARTUPINFO pointer
850 &piProcInfo); // receives PROCESS_INFORMATION
851 free((void *)exeName);
852 free((void *)cmdLine);
854 if (bFuncRetn == 0) {
855 ErrorExit("CreateProcess failed\n");
856 return INVALID_HANDLE_VALUE;
859 CloseHandle(piProcInfo.hThread);
860 return piProcInfo.hProcess;
865 ErrorExit (LPTSTR lpszMessage)
867 d_msg(__FILE__, __LINE__, 0, "%s", lpszMessage);
872 typedef struct s_bpipe {
885 int __cdecl _open_osfhandle(long, int);
888 open_bpipe(char *prog, int wait, char *mode)
890 HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
891 hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup,
892 hInputFile, hSaveStdin, hSaveStdout;
895 SECURITY_ATTRIBUTES saAttr;
898 hChildStdinRd = hChildStdinWr = hChildStdinWrDup =
899 hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup =
900 hInputFile = hSaveStdin = hSaveStdout = INVALID_HANDLE_VALUE;
902 BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
903 memset((void *)bpipe, 0, sizeof(BPIPE));
905 int mode_read = (mode[0] == 'r');
906 int mode_write = (mode[0] == 'w' || mode[1] == 'w');
909 // Set the bInheritHandle flag so pipe handles are inherited.
911 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
912 saAttr.bInheritHandle = TRUE;
913 saAttr.lpSecurityDescriptor = NULL;
915 // Save the handle to the current STDOUT.
916 hSaveStdout = GetStdHandle(STD_OUTPUT_HANDLE);
920 // Create a pipe for the child process's STDOUT.
921 if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
922 ErrorExit("Stdout pipe creation failed\n");
926 // Set a write handle to the pipe to be STDOUT.
927 if (! SetStdHandle(STD_OUTPUT_HANDLE, hChildStdoutWr))
929 ErrorExit("Redirecting STDOUT failed");
932 // Create noninheritable read handle and close the inheritable read
935 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
936 GetCurrentProcess(), &hChildStdoutRdDup , 0,
938 DUPLICATE_SAME_ACCESS);
940 ErrorExit("DuplicateHandle failed");
944 CloseHandle(hChildStdoutRd);
948 // Save the handle to the current STDIN.
950 hSaveStdin = GetStdHandle(STD_INPUT_HANDLE);
952 // Create a pipe for the child process's STDIN.
954 if (! CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
955 ErrorExit("Stdin pipe creation failed\n");
959 // Set a read handle to the pipe to be STDIN.
961 if (! SetStdHandle(STD_INPUT_HANDLE, hChildStdinRd)) {
962 ErrorExit("Redirecting Stdin failed");
966 // Duplicate the write handle to the pipe so it is not inherited.
968 fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
969 GetCurrentProcess(), &hChildStdinWrDup, 0,
970 FALSE, // not inherited
971 DUPLICATE_SAME_ACCESS);
973 ErrorExit("DuplicateHandle failed");
977 CloseHandle(hChildStdinWr);
980 bpipe->worker_pid = (pid_t)CreateChildProcess(prog);
983 bpipe->worker_stime = time(NULL);
986 SetStdHandle(STD_OUTPUT_HANDLE, hSaveStdout);
987 int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
988 bpipe->rfd = fdopen(rfd, "r");
991 SetStdHandle(STD_INPUT_HANDLE, hSaveStdin);
992 int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
993 bpipe->wfd = fdopen(wfd, "w");
997 bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
1004 free((void *) bpipe);
1008 int kill(int pid, int signal)
1011 if (!TerminateProcess((HANDLE)pid, (UINT) signal))
1014 CloseHandle((HANDLE)pid);
1018 int close_bpipe(BPIPE *bpipe)
1024 int close_wpipe(BPIPE *bpipe)