]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/win32/compat/compat.cpp
36b0fd50149b5be689099c204d640401806ca0f3
[bacula/bacula] / bacula / src / win32 / compat / compat.cpp
1 //                              -*- Mode: C++ -*- 
2 // compat.cpp -- compatibilty layer to make bacula-fd run
3 //               natively under windows
4 //
5 // Copyright (C)2004 Raider Solutions, Inc
6 // 
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.
11 //
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.
16 //
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.
21 //
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: Sun Feb 22 12:55:40 2004
26 // Update Count    : 634
27 // $Id$
28
29 #include <stdio.h>
30
31 #include "compat.h"
32 #include "pthread.h"
33
34 extern void d_msg(const char *file, int line, int level, const char *fmt,...);
35 extern DWORD   g_platform_id;
36
37 // from CYGWIN (should be diff between Jan 1 1601 and Jan 1 1970
38 #define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000I64
39
40 #define WIN32_FILETIME_SCALE  10000000             // 100ns/second
41
42 extern "C" void
43 cygwin_conv_to_win32_path(const char *name, char *win32_name)
44 {
45     const char *fname = name;
46     while (*name) {
47         /* Check for Unix separator and convert to Win32 */
48         if (*name == '/') {
49             *win32_name++ = '\\';     /* convert char */
50         /* If Win32 separated that is "quoted", remove quote */
51         } else if (*name == '\\' && name[1] == '\\') {
52             *win32_name++ = '\\';
53             name++;                   /* skip first \ */
54         } else {
55             *win32_name++ = *name;    /* copy character */
56         }
57         name++;
58     }
59     /* Strip any trailing slash, if we stored something */
60     if (*fname != 0 && win32_name[-1] == '\\') {
61         win32_name[-1] = 0;
62     } else {
63         *win32_name = 0;
64     }
65 }
66
67
68 void
69 wchar_win32_path(const char *name, WCHAR *win32_name)
70 {
71     const char *fname = name;
72     while (*name) {
73         /* Check for Unix separator and convert to Win32 */
74         if (*name == '/') {
75             *win32_name++ = '\\';     /* convert char */
76         /* If Win32 separated that is "quoted", remove quote */
77         } else if (*name == '\\' && name[1] == '\\') {
78             *win32_name++ = '\\';
79             name++;                   /* skip first \ */
80         } else {
81             *win32_name++ = *name;    /* copy character */
82         }
83         name++;
84     }
85     /* Strip any trailing slash, if we stored something */
86     if (*fname != 0 && win32_name[-1] == '\\') {
87         win32_name[-1] = 0;
88     } else {
89         *win32_name = 0;
90     }
91 }
92
93
94 int
95 open(const char *file, int flags, int mode)
96 {
97     DWORD access = 0;
98     DWORD shareMode = 0;
99     DWORD create = 0;
100     DWORD msflags = 0;
101     HANDLE foo;
102     const char *remap = file;
103
104     if (flags & O_WRONLY) access = GENERIC_WRITE;
105     else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
106     else access = GENERIC_READ;
107     
108     if (flags & O_CREAT) create = CREATE_NEW;
109     else create = OPEN_EXISTING;
110     
111     if (flags & O_TRUNC) create = TRUNCATE_EXISTING;
112     
113     if (!(flags & O_EXCL))
114         shareMode = FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE;
115     
116     if (flags & O_APPEND)
117     {
118         printf("open...APPEND not implemented yet.");
119         exit(-1);
120     }
121     
122     foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
123     if (INVALID_HANDLE_VALUE == foo)
124         return(int) -1;
125
126     return (int)foo;
127
128 }
129
130
131 int
132 close(int fd)
133 {
134     if (!CloseHandle((HANDLE)fd))
135         return -1;
136
137     return 0;
138 }
139
140 ssize_t
141 write(int fd, const void *data, size_t len)
142 {
143     BOOL status;
144     DWORD bwrite;
145     status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
146     if (status) return bwrite;
147     return -1;
148 }
149
150
151 ssize_t
152 read(int fd, void *data, size_t len)
153 {
154     BOOL status;
155     DWORD bread;
156
157     status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
158     if (status) return bread;
159     return -1;
160 }
161
162 int
163 umask(int)
164 {
165     return 0;
166 }
167
168 int
169 chmod(const char *, mode_t)
170 {
171     return 0;
172 }
173
174 int
175 chown(const char *k, uid_t, gid_t)
176 {
177     return 0;
178 }
179
180 int
181 lchown(const char *k, uid_t, gid_t)
182 {
183     return 0;
184 }
185
186
187
188 long int
189 random(void)
190 {
191     return rand();
192 }
193
194 void
195 srandom(unsigned int seed)
196 {
197     srand(seed);
198 }
199 // /////////////////////////////////////////////////////////////////
200 // convert from Windows concept of time to Unix concept of time
201 // /////////////////////////////////////////////////////////////////
202 void
203 cvt_utime_to_ftime(const time_t  &time, FILETIME &wintime)
204 {
205     uint64_t mstime = time;
206     mstime *= WIN32_FILETIME_SCALE;
207     mstime += WIN32_FILETIME_ADJUST;
208
209     wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffI64);
210     wintime.dwHighDateTime = (DWORD) ((mstime>>32)& 0xffffffffUL);
211 }
212
213 time_t
214 cvt_ftime_to_utime(const FILETIME &time)
215 {
216     uint64_t mstime = time.dwHighDateTime;
217     mstime <<= 32;
218     mstime |= time.dwLowDateTime;
219
220     mstime -= WIN32_FILETIME_ADJUST;
221     mstime /= WIN32_FILETIME_SCALE; // convert to seconds.
222
223     return (time_t) (mstime & 0xffffffff);
224 }
225
226 static const char *
227 errorString(void)
228 {
229     LPVOID lpMsgBuf;
230
231     FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
232                   FORMAT_MESSAGE_FROM_SYSTEM |
233                   FORMAT_MESSAGE_IGNORE_INSERTS,
234                   NULL,
235                   GetLastError(),
236                   MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default lang
237                   (LPTSTR) &lpMsgBuf,
238                   0,
239                   NULL);
240
241     return (const char *) lpMsgBuf;
242 }
243
244 static int
245 statDir(const char *file, struct stat *sb)
246 {
247     WIN32_FIND_DATA info;       // window's file info
248
249     if (file[1] == ':' && file[2] == 0) {
250         d_msg(__FILE__, __LINE__, 99, "faking ROOT attrs(%s).\n", file);
251         sb->st_mode = S_IFDIR;
252         sb->st_mode |= S_IREAD|S_IEXEC|S_IWRITE;
253         time(&sb->st_ctime);
254         time(&sb->st_mtime);
255         time(&sb->st_atime);
256         return 0;
257     }
258     HANDLE h = FindFirstFile(file, &info);
259
260     if (h == INVALID_HANDLE_VALUE) {
261         const char *err = errorString();
262         d_msg(__FILE__, __LINE__, 99, "FindFirstFile(%s):%s\n", file, err);
263         LocalFree((void *)err);
264         errno = GetLastError();
265         return -1;
266     }
267
268     sb->st_mode = 0777;               /* start with everything */
269     if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
270         sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
271     if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
272         sb->st_mode &= ~S_IRWXO; /* remove everything for other */
273     if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
274         sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
275     sb->st_mode |= S_IFDIR;
276
277     sb->st_size = info.nFileSizeHigh;
278     sb->st_size <<= 32;
279     sb->st_size |= info.nFileSizeLow;
280     sb->st_blksize = 4096;
281     sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
282
283     sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
284     sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
285     sb->st_ctime = cvt_ftime_to_utime(info.ftLastWriteTime);
286     FindClose(h);
287
288     return 0;
289 }
290
291 static int
292 stat2(const char *file, struct stat *sb)
293 {
294     BY_HANDLE_FILE_INFORMATION info;
295     HANDLE h;
296     int rval = 0;
297     char tmpbuf[1024];
298     cygwin_conv_to_win32_path(file, tmpbuf);
299
300     DWORD attr = GetFileAttributes(tmpbuf);
301
302     if (attr == -1) {
303         const char *err = errorString();
304         d_msg(__FILE__, __LINE__, 99,
305               "GetFileAttrubtes(%s): %s\n", tmpbuf, err);
306         LocalFree((void *)err);
307         errno = GetLastError();
308         return -1;
309     }
310     
311     if (attr & FILE_ATTRIBUTE_DIRECTORY) 
312         return statDir(tmpbuf, sb);
313
314     h = CreateFile(tmpbuf, GENERIC_READ,
315                    FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
316
317     if (h == INVALID_HANDLE_VALUE) {
318         const char *err = errorString();
319         d_msg(__FILE__, __LINE__, 99,
320               "Cannot open file for stat (%s):%s\n", tmpbuf, err);
321         LocalFree((void *)err);
322         rval = -1;
323         errno = GetLastError();
324         goto error;
325     }
326     
327     if (!GetFileInformationByHandle(h, &info)) {
328         const char *err = errorString();
329         d_msg(__FILE__, __LINE__, 99,
330               "GetfileInformationByHandle(%s): %s\n", tmpbuf, err);
331         LocalFree((void *)err);
332         rval = -1;
333         errno = GetLastError();
334         goto error;
335     }
336     
337     sb->st_dev = info.dwVolumeSerialNumber;
338     sb->st_ino = info.nFileIndexHigh;
339     sb->st_ino <<= 32;
340     sb->st_ino |= info.nFileIndexLow;
341     sb->st_nlink = (short)info.nNumberOfLinks;
342
343     sb->st_mode = 0777;               /* start with everything */
344     if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
345         sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
346     if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
347         sb->st_mode &= ~S_IRWXO; /* remove everything for other */
348     if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
349         sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
350     sb->st_mode |= S_IFREG;
351
352     sb->st_size = info.nFileSizeHigh;
353     sb->st_size <<= 32;
354     sb->st_size |= info.nFileSizeLow;
355     sb->st_blksize = 4096;
356     sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
357     sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
358     sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
359     sb->st_ctime = cvt_ftime_to_utime(info.ftLastWriteTime);
360
361 error:
362     CloseHandle(h);
363     return rval;
364 }
365
366 int
367 stat(const char *file, struct stat *sb)
368 {
369     WIN32_FILE_ATTRIBUTE_DATA data;
370     errno = 0;
371
372
373     memset(sb, 0, sizeof(*sb));
374
375     if (g_platform_id == VER_PLATFORM_WIN32_WINDOWS)
376         return stat2(file, sb);
377
378     // otherwise we're on NT
379 #if 0
380     WCHAR buf[32767];
381     buf[0] = '\\';
382     buf[1] = '\\';
383     buf[2] = '?';
384     buf[3] = '\\';
385
386     wchar_win32_path(file, buf+4);
387
388     if (!GetFileAttributesExW((WCHAR *)buf, GetFileExInfoStandard, &data))
389         return stat2(file, sb);
390 #else
391     if (!GetFileAttributesEx(file, GetFileExInfoStandard, &data))
392         return stat2(file, sb);
393 #endif
394     
395     sb->st_mode = 0777;               /* start with everything */
396     if (data.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
397         sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
398     if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
399         sb->st_mode &= ~S_IRWXO; /* remove everything for other */
400     if (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
401         sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
402
403     if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
404         sb->st_mode |= S_IFDIR;
405     else
406         sb->st_mode |= S_IFREG;
407
408     sb->st_nlink = 1;
409     sb->st_size = data.nFileSizeHigh;
410     sb->st_size <<= 32;
411     sb->st_size |= data.nFileSizeLow;
412     sb->st_blksize = 4096;
413     sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
414     sb->st_atime = cvt_ftime_to_utime(data.ftLastAccessTime);
415     sb->st_mtime = cvt_ftime_to_utime(data.ftLastWriteTime);
416     sb->st_ctime = cvt_ftime_to_utime(data.ftLastWriteTime);
417     return 0;
418 }
419
420 int
421 lstat(const char *file, struct stat *sb)
422 {
423     return stat(file, sb);
424 }
425
426 void
427 sleep(int sec)
428 {
429     Sleep(sec * 1000);
430 }    
431
432 int
433 geteuid(void)
434 {
435     return 0;
436 }
437
438 int
439 execvp(const char *, char *[]) {
440     return -1;
441 }
442
443 int
444 dup2(int, int)
445 {
446     return -1;
447 }
448
449 int
450 fork(void)
451 {
452     return -1;
453 }
454
455 int
456 pipe(int[])
457 {
458     return -1;
459 }
460
461 int
462 waitpid(int, int*, int)
463 {
464     return -1;
465 }
466
467 int
468 readlink(const char *, char *, int)
469 {
470     return -1;
471 }
472
473 off_t
474 lseek(int fd, off_t offset, int whence)
475 {
476     DWORD method = 0;
477     switch (whence) {
478     case SEEK_SET :
479         method = FILE_BEGIN;
480         break;
481     case SEEK_CUR:
482         method = FILE_CURRENT;
483         break;
484     case SEEK_END:
485         method = FILE_END;
486         break;
487     default:
488         return -1;
489     }
490     
491     return SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method);
492 }
493
494 int
495 strcasecmp(const char *s1, const char *s2)
496 {
497     register int ch1, ch2;
498     
499     if (s1==s2)
500         return 0;       /* strings are equal if same object. */
501     else if (!s1)
502         return -1;
503     else if (!s2)
504         return 1;
505     do
506     {
507         ch1 = *s1;
508         ch2 = *s2;
509         s1++;
510         s2++;
511     } while (ch1 != 0 && tolower(ch1) == tolower(ch2));
512     
513   return(ch1 - ch2);
514 }
515
516 int
517 strncasecmp(const char *s1, const char *s2, int len)
518 {
519     register int ch1, ch2;
520     
521     if (s1==s2)
522         return 0;       /* strings are equal if same object. */
523     else if (!s1)
524         return -1;
525     else if (!s2)
526         return 1;
527     do
528     {
529         ch1 = *s1;
530         ch2 = *s2;
531         s1++;
532         s2++;
533     } while (len-- && ch1 != 0 && tolower(ch1) == tolower(ch2));
534     
535     return(ch1 - ch2);
536 }
537
538 int
539 gettimeofday(struct timeval *tv, struct timezone *)
540 {
541     SYSTEMTIME now;
542     FILETIME tmp;
543     GetSystemTime(&now);
544
545     if (tv == NULL) return -1;
546     if (!SystemTimeToFileTime(&now, &tmp)) return -1;
547
548     int64_t _100nsec = tmp.dwHighDateTime;
549     _100nsec <<= 32;
550     _100nsec |= tmp.dwLowDateTime;
551     _100nsec -= WIN32_FILETIME_ADJUST;
552     
553     tv->tv_sec =(long) (_100nsec / 10000000);
554     tv->tv_usec = (long) ((_100nsec % 10000000)/10);
555     return 0;
556     
557 }
558
559 int
560 syslog(int, const char *, const char *)
561 {
562     return 0;
563 }
564
565 struct passwd *
566 getpwuid(uid_t)
567 {
568     return NULL;
569 }
570
571 struct group *
572 getgrgid(uid_t)
573 {
574     return NULL;
575 }
576
577
578 // implement opendir/readdir/closedir on top of window's API
579 typedef struct _dir
580 {
581     WIN32_FIND_DATA data;       // window's file info
582     const char *spec;           // the directory we're traversing
583     HANDLE      dirh;           // the search handle
584     BOOL        valid;          // the info in data field is valid
585     UINT32      offset;         // pseudo offset for d_off
586 } _dir;
587
588 DIR *
589 opendir(const char *path)
590 {
591     int max_len = strlen(path) + 16;
592     _dir *rval = NULL;
593     if (path == NULL) return NULL;
594     
595     rval = (_dir *)malloc(sizeof(_dir));
596     if (rval == NULL) return NULL;
597     char *tspec = (char *)malloc(max_len);
598     if (tspec == NULL) goto err1;
599     
600     if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS) {
601         // allow path to be 32767 bytes
602         tspec[0] = '\\';
603         tspec[1] = '\\';
604         tspec[2] = '?';
605         tspec[3] = '\\';
606         tspec[4] = 0;
607         cygwin_conv_to_win32_path(path, tspec+4); 
608     } else {
609         cygwin_conv_to_win32_path(path, tspec);
610     }
611     strncat(tspec, "\\*", max_len);
612     rval->spec = tspec;
613
614     rval->dirh = FindFirstFile(rval->spec, &rval->data);
615     d_msg(__FILE__, __LINE__,
616           99, "opendir(%s)\n\tspec=%s,\n\tFindFirstFile returns %d\n",
617           path, rval->spec, rval->dirh);
618
619     rval->offset = 0;
620     if (rval->dirh == INVALID_HANDLE_VALUE)
621         goto err;
622     rval->valid = 1;
623     d_msg(__FILE__, __LINE__,
624           99, "\tFirstFile=%s\n", rval->data.cFileName);
625     return (DIR *)rval;
626 err:
627     free((void *)rval->spec);
628 err1:
629     free(rval);
630     return NULL;
631 }
632     
633 int
634 closedir(DIR *dirp)
635 {
636     _dir *dp = (_dir *)dirp;
637     FindClose(dp->dirh);
638     free((void *)dp->spec);
639     free((void *)dp);
640     return 0;
641 }
642
643 /*
644   typedef struct _WIN32_FIND_DATA {
645     DWORD dwFileAttributes;
646     FILETIME ftCreationTime;
647     FILETIME ftLastAccessTime;
648     FILETIME ftLastWriteTime;
649     DWORD nFileSizeHigh;
650     DWORD nFileSizeLow;
651     DWORD dwReserved0;
652     DWORD dwReserved1;
653     TCHAR cFileName[MAX_PATH];
654     TCHAR cAlternateFileName[14];
655 } WIN32_FIND_DATA, *PWIN32_FIND_DATA;
656 */
657
658 static int
659 copyin(struct dirent &dp, const char *fname)
660 {
661     dp.d_ino = 0;
662     dp.d_reclen = 0;
663     char *cp = dp.d_name;
664     while (*fname) {
665         *cp++ = *fname++;
666         dp.d_reclen++;
667     }
668         *cp = 0;
669     return dp.d_reclen;
670 }
671 int
672 readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
673 {
674
675     _dir *dp = (_dir *)dirp;
676     if (dp->valid) {
677         entry->d_off = dp->offset;
678         dp->offset += copyin(*entry, dp->data.cFileName);
679         *result = entry;              /* return entry address */
680         d_msg(__FILE__, __LINE__,
681               99, "readdir_r(%p, { d_name=\"%s\", d_reclen=%d, d_off=%d\n",
682               dirp, entry->d_name, entry->d_reclen, entry->d_off);
683     } else {
684 //      d_msg(__FILE__, __LINE__, 99, "readdir_r !valid\n");
685         return -1;
686     }
687     dp->valid = FindNextFile(dp->dirh, &dp->data);
688     return 0;
689 }
690
691
692 int
693 inet_aton(const char *a, struct in_addr *inp)
694 {
695
696     const char *cp = a;
697     uint32_t acc = 0, tmp = 0;
698     int dotc = 0;
699     if (!isdigit(*a)) return 0;
700     while (*cp) {
701         if (isdigit(*cp))
702             tmp = (tmp * 10) + (*cp -'0');
703         else if (*cp == '.') {
704             if (tmp > 255) return 0;
705             acc = (acc << 8) + tmp;
706             dotc++;
707         }
708         else return 0;
709     }
710
711     if (dotc != 3) return 0;
712     inp->s_addr = acc;
713     return 1;
714 }
715
716 int
717 nanosleep(const struct timespec *req, struct timespec *rem)
718 {
719     if (rem)
720         rem->tv_sec = rem->tv_nsec = 0;
721     Sleep((req->tv_sec * 1000) + (req->tv_nsec/100000));
722     return 0;
723 }
724
725 void
726 init_signals(void terminate(int sig))
727 {
728
729 }
730
731 void
732 init_stack_dump(void)
733 {
734
735 }
736
737
738 long
739 pathconf(const char *path, int name)
740 {
741     switch(name) {
742     case _PC_PATH_MAX :
743         if (strncmp(path, "\\\\?\\", 4) == 0)
744             return 32767;
745     case _PC_NAME_MAX :
746         return 255;
747     }
748
749     return -1;
750 }
751
752 int
753 WSA_Init(void)
754 {
755     WORD wVersionRequested = MAKEWORD( 1, 1);
756     WSADATA wsaData;
757     
758     int err = WSAStartup(wVersionRequested, &wsaData);
759     
760     
761     if (err != 0)
762     {
763         printf("Can not start Windows Sockets\n");
764         return -1;
765     }
766
767     return 0;
768 }
769
770
771 int
772 win32_chdir(const char *dir)
773 {
774     if (0 == SetCurrentDirectory(dir)) return -1;
775     return 0;
776 }
777
778 char *
779 win32_getcwd(char *buf, int maxlen)
780 {
781    int n =  GetCurrentDirectory(maxlen, buf);
782
783    if (n == 0 || n > maxlen) return NULL;
784
785    if (n+1 > maxlen) return NULL;
786    if (n != 3) {
787        buf[n] = '\\';
788        buf[n+1] = 0;
789    }
790    
791    return buf;
792 }
793
794 #include "mswinver.h"
795
796 char WIN_VERSION_LONG[64];
797 char WIN_VERSION[32];
798
799 class winver {
800 public:
801     winver(void);
802 };
803
804 static winver INIT;                     // cause constructor to be called before main()
805
806 #include "bacula.h"
807 #include "jcr.h"
808
809 winver::winver(void)
810 {
811     const char *version = "";
812     const char *platform = "";
813     OSVERSIONINFO osvinfo;
814     osvinfo.dwOSVersionInfoSize = sizeof(osvinfo);
815
816     // Get the current OS version
817     if (!GetVersionEx(&osvinfo)) {
818         version = "Unknown";
819         platform = "Unknown";
820     }
821     else
822         switch (_mkversion(osvinfo.dwPlatformId, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion))
823         {
824         case MS_WINDOWS_95: (version =  "Windows 95"); break;
825         case MS_WINDOWS_98: (version =  "Windows 98"); break;
826         case MS_WINDOWS_ME: (version =  "Windows ME"); break;
827         case MS_WINDOWS_NT4:(version =  "Windows NT 4.0"); platform = "NT"; break;
828         case MS_WINDOWS_2K: (version =  "Windows 2000");platform = "NT"; break;
829         case MS_WINDOWS_XP: (version =  "Windows XP");platform = "NT"; break;
830         case MS_WINDOWS_S2003: (version =  "Windows Server 2003");platform = "NT"; break;
831         default: version = "Windows ??"; break;
832         }
833
834     bstrncpy(WIN_VERSION_LONG, version, sizeof(WIN_VERSION_LONG));
835     snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %d.%d.%d",
836              platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
837
838 #if 0
839     BPIPE *b = open_bpipe("ls -l", 10, "r");
840     char buf[1024];
841     while (!feof(b->rfd)) {
842         fgets(buf, sizeof(buf), b->rfd);
843     }
844     close_bpipe(b);
845 #endif
846 }
847  
848 BOOL CreateChildProcess(VOID); 
849 VOID WriteToPipe(VOID); 
850 VOID ReadFromPipe(VOID); 
851 VOID ErrorExit(LPTSTR); 
852 VOID ErrMsg(LPTSTR, BOOL); 
853  
854
855 const char *
856 getArgv0(const char *cmdline)
857 {
858     const char *cp = cmdline;
859
860     while (*cp && !isspace(*cp)) cp++;
861
862     int len = cp - cmdline;
863     char *rval = (char *)malloc(len+1);
864
865     cp = cmdline;
866     char *rp = rval;
867     while (len--)
868         *rp++ = *cp++;
869
870     *rp = 0;
871     return rval;
872 }
873
874 HANDLE
875 CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err) 
876
877     PROCESS_INFORMATION piProcInfo; 
878     STARTUPINFO siStartInfo;
879     BOOL bFuncRetn = FALSE; 
880     
881     // Set up members of the PROCESS_INFORMATION structure. 
882     
883     ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
884     
885     // Set up members of the STARTUPINFO structure. 
886     
887     ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
888     siStartInfo.cb = sizeof(STARTUPINFO);
889     // setup new process to use supplied handles for stdin,stdout,stderr
890     // if supplied handles are not used the send a copy of our STD_HANDLE
891     // as appropriate
892     siStartInfo.dwFlags = STARTF_USESTDHANDLES;
893
894     if (in != INVALID_HANDLE_VALUE)
895         siStartInfo.hStdInput = in;
896     else
897         siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
898     
899     if (out != INVALID_HANDLE_VALUE)
900         siStartInfo.hStdOutput = out;
901     else
902         siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
903     if (err != INVALID_HANDLE_VALUE)
904         siStartInfo.hStdError = err;
905     else
906         siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
907     // Create the child process. 
908     
909     char cmdLine[1024];
910     char exeFile[1024];
911     // retrive the first compont of the command line which should be the
912     // executable 
913     const char *exeName = getArgv0(cmdline);
914     // check to see if absolute path was passed to us already?
915     if (exeName[1] != ':'
916         || (strchr(cmdline, '/') == NULL
917             && strchr(cmdline, '\\') == NULL))
918     {
919         // only command name so perform search of PATH to find 
920         char *file;
921         DWORD rval = SearchPath(NULL,
922                                 exeName,
923                                 ".exe",
924                                 sizeof(exeFile),
925                                 exeFile,
926                                 &file);
927         if (rval == 0)
928             return INVALID_HANDLE_VALUE;
929         if (rval > sizeof(exeFile))
930             return INVALID_HANDLE_VALUE;
931
932     }
933     else 
934         strcpy(exeFile, exeName);
935
936     // exeFile now has absolute path to program to execute.
937     free((void *)exeName);
938     // copy original command line to pass to create process
939     strcpy(cmdLine, cmdline);
940     // try to execute program
941     bFuncRetn = CreateProcess(exeFile, 
942                               cmdLine, // command line 
943                               NULL, // process security attributes 
944                               NULL, // primary thread security attributes 
945                               TRUE, // handles are inherited 
946                               0, // creation flags 
947                               NULL, // use parent's environment 
948                               NULL, // use parent's current directory 
949                               &siStartInfo, // STARTUPINFO pointer 
950                               &piProcInfo); // receives PROCESS_INFORMATION
951     
952     if (bFuncRetn == 0) {
953         ErrorExit("CreateProcess failed\n");
954         return INVALID_HANDLE_VALUE;
955     }
956     // we don't need a handle on the process primary thread so we close
957     // this now.
958     CloseHandle(piProcInfo.hThread);
959     
960     return piProcInfo.hProcess;
961 }
962
963  
964 void
965 ErrorExit (LPTSTR lpszMessage) 
966
967     d_msg(__FILE__, __LINE__, 0, "%s", lpszMessage);
968
969  
970
971 /*
972 typedef struct s_bpipe {
973    pid_t worker_pid;
974    time_t worker_stime;
975    int wait;
976    btimer_t *timer_id;
977    FILE *rfd;
978    FILE *wfd;
979 } BPIPE;
980 */
981
982 static void
983 CloseIfValid(HANDLE handle)
984 {
985     if (handle != INVALID_HANDLE_VALUE)
986         CloseHandle(handle);
987 }
988 // include <io.h> causes to many conflicts with some of
989 // the fuctions we define here.
990 extern "C" {
991 int __cdecl _open_osfhandle(long, int);
992 }
993
994 BPIPE *
995 open_bpipe(char *prog, int wait, const char *mode)
996 {
997     HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup, 
998         hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup, 
999         hInputFile;
1000     
1001     SECURITY_ATTRIBUTES saAttr; 
1002
1003     BOOL fSuccess; 
1004
1005     hChildStdinRd = hChildStdinWr = hChildStdinWrDup = 
1006         hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup = 
1007         hInputFile = INVALID_HANDLE_VALUE;
1008     
1009     BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
1010     memset((void *)bpipe, 0, sizeof(BPIPE));
1011
1012     int mode_read = (mode[0] == 'r');
1013     int mode_write = (mode[0] == 'w' || mode[1] == 'w');
1014     
1015     
1016     // Set the bInheritHandle flag so pipe handles are inherited. 
1017     
1018     saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
1019     saAttr.bInheritHandle = TRUE; 
1020     saAttr.lpSecurityDescriptor = NULL; 
1021     
1022     if (mode_read) {
1023         
1024         // Create a pipe for the child process's STDOUT. 
1025         if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
1026             ErrorExit("Stdout pipe creation failed\n");
1027             goto cleanup;
1028         }
1029         // Create noninheritable read handle and close the inheritable read 
1030         // handle. 
1031         
1032         fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
1033                                    GetCurrentProcess(), &hChildStdoutRdDup , 0,
1034                                    FALSE,
1035                                    DUPLICATE_SAME_ACCESS);
1036         if( !fSuccess ) {
1037             ErrorExit("DuplicateHandle failed");
1038             goto cleanup;
1039         }
1040         
1041         CloseHandle(hChildStdoutRd);
1042     }
1043     
1044     if (mode_write) {
1045         
1046         // Create a pipe for the child process's STDIN. 
1047         
1048         if (! CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
1049             ErrorExit("Stdin pipe creation failed\n");
1050             goto cleanup;
1051         }
1052         
1053         // Duplicate the write handle to the pipe so it is not inherited. 
1054         fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr, 
1055                                    GetCurrentProcess(), &hChildStdinWrDup,
1056                                    0, 
1057                                    FALSE,                  // not inherited 
1058                                    DUPLICATE_SAME_ACCESS); 
1059         if (!fSuccess) {
1060             ErrorExit("DuplicateHandle failed");
1061             goto cleanup;
1062         }
1063         
1064         CloseHandle(hChildStdinWr); 
1065     }
1066     // spawn program with redirected handles as appropriate
1067     bpipe->worker_pid = (pid_t)
1068         CreateChildProcess(prog, // commandline
1069                            hChildStdinRd, // stdin HANDLE
1070                            hChildStdoutWr, // stdout HANDLE
1071                            hChildStdoutWr);// stderr HANDLE
1072     
1073     if ((HANDLE) bpipe->worker_pid == INVALID_HANDLE_VALUE)
1074         goto cleanup;
1075     
1076     bpipe->wait = wait;
1077     bpipe->worker_stime = time(NULL);
1078     
1079     if (mode_read) {
1080         CloseHandle(hChildStdoutWr); // close our write side so when
1081                                      // process terminates we can
1082                                      // detect eof.
1083         // ugly but convert WIN32 HANDLE to FILE*
1084         int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
1085         bpipe->rfd = _fdopen(rfd, "r");
1086     }
1087     if (mode_write) {
1088         CloseHandle(hChildStdinRd); // close our read side so as not
1089                                     // to interfre with child's copy
1090         // ugly but convert WIN32 HANDLE to FILE*
1091         int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
1092         bpipe->wfd = _fdopen(wfd, "w");
1093     }
1094     
1095     if (wait > 0) {
1096         bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
1097     }
1098     
1099     return bpipe;
1100     
1101 cleanup:
1102     
1103     CloseIfValid(hChildStdoutRd);
1104     CloseIfValid(hChildStdoutRdDup);
1105     CloseIfValid(hChildStdinWr);
1106     CloseIfValid(hChildStdinWrDup);
1107     
1108     free((void *) bpipe);
1109     
1110     return NULL;
1111 }
1112
1113 int
1114 kill(int pid, int signal)
1115 {
1116     int rval = 0;
1117     if (!TerminateProcess((HANDLE)pid, (UINT) signal))
1118         rval = -1;
1119     CloseHandle((HANDLE)pid);
1120     return rval;
1121 }
1122
1123 int
1124 close_bpipe(BPIPE *bpipe)
1125 {
1126     int rval = 0;
1127     if (bpipe->rfd) fclose(bpipe->rfd);
1128     if (bpipe->wfd) fclose(bpipe->wfd);
1129
1130     if (bpipe->wait) {
1131         int remaining_wait = bpipe->wait;
1132         do 
1133         {
1134             DWORD exitCode;
1135             if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode))
1136             {
1137                 const char *err = errorString();
1138                 rval = GetLastError();
1139                 d_msg(__FILE__, __LINE__, 0, 
1140                       "GetExitCode error %s\n", err);
1141                 LocalFree((void *)err);
1142                 break;
1143             }
1144             
1145             if (exitCode == STILL_ACTIVE) {
1146                 bmicrosleep(1, 0);             /* wait one second */
1147                 remaining_wait--;
1148             }
1149             else break;
1150         } while(remaining_wait);
1151     }
1152     
1153     if (bpipe->timer_id) {
1154         stop_child_timer(bpipe->timer_id);
1155     }
1156     free((void *)bpipe);    
1157     return rval;
1158 }
1159
1160 int
1161 close_wpipe(BPIPE *bpipe)
1162 {
1163     int stat = 1;
1164     
1165     if (bpipe->wfd) {
1166         fflush(bpipe->wfd);
1167         if (fclose(bpipe->wfd) != 0) {
1168             stat = 0;
1169       }
1170         bpipe->wfd = NULL;
1171     }
1172     return stat;
1173 }
1174
1175 #include "findlib/find.h"
1176
1177 int
1178 utime(const char *fname, struct utimbuf *times)
1179 {
1180     FILETIME acc, mod;
1181     char tmpbuf[1024];
1182
1183     cygwin_conv_to_win32_path(fname, tmpbuf);
1184
1185     cvt_utime_to_ftime(times->actime, acc);
1186     cvt_utime_to_ftime(times->modtime, mod);
1187
1188     HANDLE h = CreateFile(tmpbuf,
1189                           FILE_WRITE_ATTRIBUTES,
1190                           FILE_SHARE_WRITE,
1191                           NULL,
1192                           OPEN_EXISTING,
1193                           0,
1194                           NULL);
1195
1196     if (h == INVALID_HANDLE_VALUE) {
1197         const char *err = errorString();
1198         d_msg(__FILE__, __LINE__, 99,
1199               "Cannot open file for stat (%s):%s\n", tmpbuf, err);
1200         LocalFree((void *)err);
1201         return -1;
1202     }
1203
1204     int rval = SetFileTime(h, NULL, &acc, &mod) ? 0 : -1;
1205
1206     CloseHandle(h);
1207     
1208     return rval;
1209 }
1210