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