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