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