]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/win32/compat/compat.cpp
285786826a5c1a9a05cc4e2da8d99b476e7d98dd
[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-2005 Kern Sibbald
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
12 //  version 2 as amended with additional clauses defined in the
13 //  file LICENSE in the main source directory.
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 
18 //  the file LICENSE for additional details.
19 //
20 // Author          : Christopher S. Hull
21 // Created On      : Sat Jan 31 15:55:00 2004
22 // $Id$
23
24 #include "bacula.h"
25
26 #ifdef WIN32_VSS
27 #include "vss.h"
28 #endif 
29
30 #include "../../lib/winapi.h"
31
32
33 /* to allow the usage of the original version in this file here */
34 #undef fputs
35
36 #define b_errno_win32 (1<<29)
37
38 #define USE_WIN32_COMPAT_IO 1
39
40 extern void d_msg(const char *file, int line, int level, const char *fmt,...);
41 extern DWORD   g_platform_id;
42 extern int enable_vss;  
43
44 // from MicroSoft SDK (KES) is the diff between Jan 1 1601 and Jan 1 1970
45 #ifdef HAVE_MINGW
46 #define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000UL //Not sure it works
47 #else
48 #define WIN32_FILETIME_ADJUST 0x19DB1DED53E8000I64
49 #endif
50
51 #define WIN32_FILETIME_SCALE  10000000             // 100ns/second
52
53 extern "C" void
54 cygwin_conv_to_win32_path(const char *name, char *win32_name, DWORD dwSize)
55 {
56     const char *fname = name;
57     char *tname = win32_name;
58     while (*name) {
59         /* Check for Unix separator and convert to Win32 */
60         if (name[0] == '/' && name[1] == '/') {  /* double slash? */
61            name++;                               /* yes, skip first one */
62         }
63         if (*name == '/') {
64             *win32_name++ = '\\';     /* convert char */
65         /* If Win32 separated that is "quoted", remove quote */
66         } else if (*name == '\\' && name[1] == '\\') {
67             *win32_name++ = '\\';
68             name++;                   /* skip first \ */
69         } else {
70             *win32_name++ = *name;    /* copy character */
71         }
72         name++;
73     }
74     /* Strip any trailing slash, if we stored something */
75     if (*fname != 0 && win32_name[-1] == '\\') {
76         win32_name[-1] = 0;
77     } else {
78         *win32_name = 0;
79     }
80
81 #ifdef WIN32_VSS
82     /* here we convert to VSS specific file name which
83        can get longer because VSS will make something like
84        \\\\?\\GLOBALROOT\\Device\\HarddiskVolumeShadowCopy1\\bacula\\uninstall.exe
85        from c:\bacula\uninstall.exe
86     */ 
87     if (g_pVSSClient && enable_vss == 1) {
88        POOLMEM *pszBuf = get_pool_memory (PM_FNAME);
89        pszBuf = check_pool_memory_size(pszBuf, dwSize);
90        bstrncpy(pszBuf, tname, strlen(tname)+1);
91        g_pVSSClient->GetShadowPath(pszBuf, tname, dwSize);
92        free_pool_memory(pszBuf);
93     }
94 #endif
95 }
96
97 int 
98 wchar_2_UTF8(char *pszUTF, const WCHAR *pszUCS, int cchChar)
99 {
100    /* the return value is the number of bytes written to the buffer. 
101       The number includes the byte for the null terminator. */
102
103    if (p_WideCharToMultiByte) {
104          int nRet = p_WideCharToMultiByte(CP_UTF8,0,pszUCS,-1,pszUTF,cchChar,NULL,NULL);
105          ASSERT (nRet > 0);
106          return nRet;
107       }
108    else
109       return NULL;
110 }
111
112 int 
113 UTF8_2_wchar(POOLMEM **ppszUCS, const char *pszUTF)
114 {
115    /* the return value is the number of wide characters written to the buffer. */
116    /* convert null terminated string from utf-8 to ucs2, enlarge buffer if necessary */
117
118    if (p_MultiByteToWideChar) {
119       /* strlen of UTF8 +1 is enough */ 
120       DWORD cchSize = (strlen(pszUTF)+1);
121       *ppszUCS = check_pool_memory_size(*ppszUCS, cchSize*sizeof (WCHAR));
122       
123       int nRet = p_MultiByteToWideChar(CP_UTF8, 0, pszUTF, -1, (LPWSTR) *ppszUCS,cchSize);
124       ASSERT (nRet > 0);
125       return nRet;
126    }
127    else
128       return NULL;
129 }
130
131
132 void
133 wchar_win32_path(const char *name, WCHAR *win32_name)
134 {
135     const char *fname = name;
136     while (*name) {
137         /* Check for Unix separator and convert to Win32 */
138         if (*name == '/') {
139             *win32_name++ = '\\';     /* convert char */
140         /* If Win32 separated that is "quoted", remove quote */
141         } else if (*name == '\\' && name[1] == '\\') {
142             *win32_name++ = '\\';
143             name++;                   /* skip first \ */
144         } else {
145             *win32_name++ = *name;    /* copy character */
146         }
147         name++;
148     }
149     /* Strip any trailing slash, if we stored something */
150     if (*fname != 0 && win32_name[-1] == '\\') {
151         win32_name[-1] = 0;
152     } else {
153         *win32_name = 0;
154     }
155 }
156
157 int umask(int)
158 {
159    return 0;
160 }
161
162 int chmod(const char *, mode_t)
163 {
164    return 0;
165 }
166
167 int chown(const char *k, uid_t, gid_t)
168 {
169    return 0;
170 }
171
172 int lchown(const char *k, uid_t, gid_t)
173 {
174    return 0;
175 }
176
177 #ifdef needed
178 bool fstype(const char *fname, char *fs, int fslen)
179 {
180    return true;                       /* accept anything */
181 }
182 #endif
183
184
185 long int
186 random(void)
187 {
188     return rand();
189 }
190
191 void
192 srandom(unsigned int seed)
193 {
194    srand(seed);
195 }
196 // /////////////////////////////////////////////////////////////////
197 // convert from Windows concept of time to Unix concept of time
198 // /////////////////////////////////////////////////////////////////
199 void
200 cvt_utime_to_ftime(const time_t  &time, FILETIME &wintime)
201 {
202     uint64_t mstime = time;
203     mstime *= WIN32_FILETIME_SCALE;
204     mstime += WIN32_FILETIME_ADJUST;
205
206     #ifdef HAVE_MINGW
207     wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffUL);
208     #else
209     wintime.dwLowDateTime = (DWORD)(mstime & 0xffffffffI64);
210     #endif
211     wintime.dwHighDateTime = (DWORD) ((mstime>>32)& 0xffffffffUL);
212 }
213
214 time_t
215 cvt_ftime_to_utime(const FILETIME &time)
216 {
217     uint64_t mstime = time.dwHighDateTime;
218     mstime <<= 32;
219     mstime |= time.dwLowDateTime;
220
221     mstime -= WIN32_FILETIME_ADJUST;
222     mstime /= WIN32_FILETIME_SCALE; // convert to seconds.
223
224     return (time_t) (mstime & 0xffffffff);
225 }
226
227 static const char *
228 errorString(void)
229 {
230    LPVOID lpMsgBuf;
231
232    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
233                  FORMAT_MESSAGE_FROM_SYSTEM |
234                  FORMAT_MESSAGE_IGNORE_INSERTS,
235                  NULL,
236                  GetLastError(),
237                  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default lang
238                  (LPTSTR) &lpMsgBuf,
239                  0,
240                  NULL);
241
242    return (const char *) lpMsgBuf;
243 }
244
245 #ifndef HAVE_MINGW
246
247 static int
248 statDir(const char *file, struct stat *sb)
249 {
250    WIN32_FIND_DATAW info_w;       // window's file info
251    WIN32_FIND_DATAA info_a;       // window's file info
252
253    // cache some common vars to make code more transparent
254    DWORD* pdwFileAttributes;
255    DWORD* pnFileSizeHigh;
256    DWORD* pnFileSizeLow;
257    FILETIME* pftLastAccessTime;
258    FILETIME* pftLastWriteTime;
259    FILETIME* pftCreationTime;
260
261    if (file[1] == ':' && file[2] == 0) {
262         d_msg(__FILE__, __LINE__, 99, "faking ROOT attrs(%s).\n", file);
263         sb->st_mode = S_IFDIR;
264         sb->st_mode |= S_IREAD|S_IEXEC|S_IWRITE;
265         time(&sb->st_ctime);
266         time(&sb->st_mtime);
267         time(&sb->st_atime);
268         return 0;
269     }
270
271    HANDLE h = INVALID_HANDLE_VALUE;
272
273    // use unicode or ascii
274    if (p_FindFirstFileW) {
275       POOLMEM* pwszBuf = get_pool_memory (PM_FNAME);         
276       UTF8_2_wchar(&pwszBuf, file);
277       
278       h = p_FindFirstFileW((LPCWSTR) pwszBuf, &info_w);
279       free_pool_memory(pwszBuf);
280
281       pdwFileAttributes = &info_w.dwFileAttributes;
282       pnFileSizeHigh    = &info_w.nFileSizeHigh;
283       pnFileSizeLow     = &info_w.nFileSizeLow;
284       pftLastAccessTime = &info_w.ftLastAccessTime;
285       pftLastWriteTime  = &info_w.ftLastWriteTime;
286       pftCreationTime   = &info_w.ftCreationTime;
287    }
288    else if (p_FindFirstFileA) {
289       h = p_FindFirstFileA(file, &info_a);
290
291       pdwFileAttributes = &info_a.dwFileAttributes;
292       pnFileSizeHigh    = &info_a.nFileSizeHigh;
293       pnFileSizeLow     = &info_a.nFileSizeLow;
294       pftLastAccessTime = &info_a.ftLastAccessTime;
295       pftLastWriteTime  = &info_a.ftLastWriteTime;
296       pftCreationTime   = &info_a.ftCreationTime;
297    }
298
299     if (h == INVALID_HANDLE_VALUE) {
300         const char *err = errorString();
301         d_msg(__FILE__, __LINE__, 99, "FindFirstFile(%s):%s\n", file, err);
302         LocalFree((void *)err);
303         errno = b_errno_win32;
304         return -1;
305     }
306
307     sb->st_mode = 0777;               /* start with everything */
308     if (*pdwFileAttributes & FILE_ATTRIBUTE_READONLY)
309         sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
310     if (*pdwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
311         sb->st_mode &= ~S_IRWXO; /* remove everything for other */
312     if (*pdwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
313         sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
314     sb->st_mode |= S_IFDIR;
315
316     sb->st_size = *pnFileSizeHigh;
317     sb->st_size <<= 32;
318     sb->st_size |= *pnFileSizeLow;
319     sb->st_blksize = 4096;
320     sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
321
322     sb->st_atime = cvt_ftime_to_utime(*pftLastAccessTime);
323     sb->st_mtime = cvt_ftime_to_utime(*pftLastWriteTime);
324     sb->st_ctime = cvt_ftime_to_utime(*pftCreationTime);
325     FindClose(h);
326
327     return 0;
328 }
329
330 static int
331 stat2(const char *file, struct stat *sb)
332 {
333     BY_HANDLE_FILE_INFORMATION info;
334     HANDLE h;
335     int rval = 0;
336     char tmpbuf[1024];
337     cygwin_conv_to_win32_path(file, tmpbuf, 1024);
338
339     DWORD attr = -1;
340
341     if (p_GetFileAttributesW) {
342       POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
343       UTF8_2_wchar(&pwszBuf, tmpbuf);
344       
345       attr = p_GetFileAttributesW((LPCWSTR) pwszBuf);
346       free_pool_memory(pwszBuf);
347     }
348     else if (p_GetFileAttributesA) {
349        attr = p_GetFileAttributesA(tmpbuf);
350     }
351
352     if (attr == -1) {
353         const char *err = errorString();
354         d_msg(__FILE__, __LINE__, 99,
355               "GetFileAttrubtes(%s): %s\n", tmpbuf, err);
356         LocalFree((void *)err);
357         errno = b_errno_win32;
358         return -1;
359     }
360
361     if (attr & FILE_ATTRIBUTE_DIRECTORY)
362         return statDir(tmpbuf, sb);
363
364     h = CreateFileA(tmpbuf, GENERIC_READ,
365                    FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
366
367     if (h == INVALID_HANDLE_VALUE) {
368         const char *err = errorString();
369         d_msg(__FILE__, __LINE__, 99,
370               "Cannot open file for stat (%s):%s\n", tmpbuf, err);
371         LocalFree((void *)err);
372         rval = -1;
373         errno = b_errno_win32;
374         goto error;
375     }
376
377     if (!GetFileInformationByHandle(h, &info)) {
378         const char *err = errorString();
379         d_msg(__FILE__, __LINE__, 99,
380               "GetfileInformationByHandle(%s): %s\n", tmpbuf, err);
381         LocalFree((void *)err);
382         rval = -1;
383         errno = b_errno_win32;
384         goto error;
385     }
386
387     sb->st_dev = info.dwVolumeSerialNumber;
388     sb->st_ino = info.nFileIndexHigh;
389     sb->st_ino <<= 32;
390     sb->st_ino |= info.nFileIndexLow;
391     sb->st_nlink = (short)info.nNumberOfLinks;
392     if (sb->st_nlink > 1) {
393        d_msg(__FILE__, __LINE__, 99,  "st_nlink=%d\n", sb->st_nlink);
394     }
395
396     sb->st_mode = 0777;               /* start with everything */
397     if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
398         sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
399     if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
400         sb->st_mode &= ~S_IRWXO; /* remove everything for other */
401     if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
402         sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
403     sb->st_mode |= S_IFREG;
404
405     sb->st_size = info.nFileSizeHigh;
406     sb->st_size <<= 32;
407     sb->st_size |= info.nFileSizeLow;
408     sb->st_blksize = 4096;
409     sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
410     sb->st_atime = cvt_ftime_to_utime(info.ftLastAccessTime);
411     sb->st_mtime = cvt_ftime_to_utime(info.ftLastWriteTime);
412     sb->st_ctime = cvt_ftime_to_utime(info.ftCreationTime);
413
414 error:
415     CloseHandle(h);
416     return rval;
417 }
418
419 int
420 stat(const char *file, struct stat *sb)
421 {
422     WIN32_FILE_ATTRIBUTE_DATA data;
423     errno = 0;
424
425
426     memset(sb, 0, sizeof(*sb));
427
428     if (g_platform_id == VER_PLATFORM_WIN32_WINDOWS)
429         return stat2(file, sb);
430
431     // otherwise we're on NT
432 #if 0
433     WCHAR buf[32767];
434     buf[0] = '\\';
435     buf[1] = '\\';
436     buf[2] = '?';
437     buf[3] = '\\';
438
439     wchar_win32_path(file, buf+4);
440
441     if (!GetFileAttributesExW((WCHAR *)buf, GetFileExInfoStandard, &data))
442         return stat2(file, sb);
443 #else
444
445     if (p_GetFileAttributesExW) {
446       /* dynamically allocate enough space for UCS2 filename */
447       POOLMEM* pwszBuf = get_pool_memory (PM_FNAME);          
448       UTF8_2_wchar(&pwszBuf, file);
449
450       BOOL b = p_GetFileAttributesExW((LPCWSTR) pwszBuf, GetFileExInfoStandard, &data);
451       free_pool_memory(pwszBuf);
452                         
453       if (!b) 
454          return stat2(file, sb);
455       
456     } else if (p_GetFileAttributesExA) {
457          if (!p_GetFileAttributesExA(file, GetFileExInfoStandard, &data))
458             return stat2(file, sb);
459     }
460     else
461        return stat2(file, sb);
462
463 #endif
464
465     sb->st_mode = 0777;               /* start with everything */
466     if (data.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
467         sb->st_mode &= ~(S_IRUSR|S_IRGRP|S_IROTH);
468     if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
469         sb->st_mode &= ~S_IRWXO; /* remove everything for other */
470     if (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
471         sb->st_mode |= S_ISVTX; /* use sticky bit -> hidden */
472
473     if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
474         sb->st_mode |= S_IFDIR;
475     else
476         sb->st_mode |= S_IFREG;
477
478     sb->st_nlink = 1;
479     sb->st_size = data.nFileSizeHigh;
480     sb->st_size <<= 32;
481     sb->st_size |= data.nFileSizeLow;
482     sb->st_blksize = 4096;
483     sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
484     sb->st_atime = cvt_ftime_to_utime(data.ftLastAccessTime);
485     sb->st_mtime = cvt_ftime_to_utime(data.ftLastWriteTime);
486     sb->st_ctime = cvt_ftime_to_utime(data.ftCreationTime);
487     return 0;
488 }
489
490 #endif //HAVE_MINGW
491
492 int
493 lstat(const char *file, struct stat *sb)
494 {
495     return stat(file, sb);
496 }
497
498 void
499 sleep(int sec)
500 {
501     Sleep(sec * 1000);
502 }
503
504 int
505 geteuid(void)
506 {
507     return 0;
508 }
509
510 int
511 execvp(const char *, char *[]) {
512     errno = ENOSYS;
513     return -1;
514 }
515
516
517 int
518 fork(void)
519 {
520     errno = ENOSYS;
521     return -1;
522 }
523
524 int
525 pipe(int[])
526 {
527     errno = ENOSYS;
528     return -1;
529 }
530
531 int
532 waitpid(int, int*, int)
533 {
534     errno = ENOSYS;
535     return -1;
536 }
537
538 int
539 readlink(const char *, char *, int)
540 {
541     errno = ENOSYS;
542     return -1;
543 }
544
545
546 #ifndef HAVE_MINGW
547 int
548 strcasecmp(const char *s1, const char *s2)
549 {
550     register int ch1, ch2;
551
552     if (s1==s2)
553         return 0;       /* strings are equal if same object. */
554     else if (!s1)
555         return -1;
556     else if (!s2)
557         return 1;
558     do
559     {
560         ch1 = *s1;
561         ch2 = *s2;
562         s1++;
563         s2++;
564     } while (ch1 != 0 && tolower(ch1) == tolower(ch2));
565
566   return(ch1 - ch2);
567 }
568 #endif //HAVE_MINGW
569
570 int
571 strncasecmp(const char *s1, const char *s2, int len)
572 {
573     register int ch1, ch2;
574
575     if (s1==s2)
576         return 0;       /* strings are equal if same object. */
577     else if (!s1)
578         return -1;
579     else if (!s2)
580         return 1;
581     while (len--)
582     {
583         ch1 = *s1;
584         ch2 = *s2;
585         s1++;
586         s2++;
587         if (ch1 == 0 || tolower(ch1) != tolower(ch2)) break;
588     } 
589
590     return (ch1 - ch2);
591 }
592
593 int
594 gettimeofday(struct timeval *tv, struct timezone *)
595 {
596     SYSTEMTIME now;
597     FILETIME tmp;
598     GetSystemTime(&now);
599
600     if (tv == NULL) {
601        errno = EINVAL;
602        return -1;
603     }
604     if (!SystemTimeToFileTime(&now, &tmp)) {
605        errno = b_errno_win32;
606        return -1;
607     }
608
609     int64_t _100nsec = tmp.dwHighDateTime;
610     _100nsec <<= 32;
611     _100nsec |= tmp.dwLowDateTime;
612     _100nsec -= WIN32_FILETIME_ADJUST;
613
614     tv->tv_sec =(long) (_100nsec / 10000000);
615     tv->tv_usec = (long) ((_100nsec % 10000000)/10);
616     return 0;
617
618 }
619
620 int
621 syslog(int type, const char *fmt, const char *msg)
622 {
623 /*#ifndef HAVE_CONSOLE
624     MessageBox(NULL, msg, "Bacula", MB_OK);
625 #endif*/
626     return 0;
627 }
628
629 struct passwd *
630 getpwuid(uid_t)
631 {
632     return NULL;
633 }
634
635 struct group *
636 getgrgid(uid_t)
637 {
638     return NULL;
639 }
640
641 // implement opendir/readdir/closedir on top of window's API
642
643 typedef struct _dir
644 {
645     WIN32_FIND_DATAA data_a;    // window's file info (ansii version)
646     WIN32_FIND_DATAW data_w;    // window's file info (wchar version)
647     const char *spec;           // the directory we're traversing
648     HANDLE      dirh;           // the search handle
649     BOOL        valid_a;        // the info in data_a field is valid
650     BOOL        valid_w;        // the info in data_w field is valid
651     UINT32      offset;         // pseudo offset for d_off
652 } _dir;
653
654 DIR *
655 opendir(const char *path)
656 {
657     /* enough space for VSS !*/
658     int max_len = strlen(path) + MAX_PATH;
659     _dir *rval = NULL;
660     if (path == NULL) {
661        errno = ENOENT;
662        return NULL;
663     }
664
665     rval = (_dir *)malloc(sizeof(_dir));
666     memset (rval, 0, sizeof (_dir));
667     if (rval == NULL) return NULL;
668     char *tspec = (char *)malloc(max_len);
669     if (tspec == NULL) return NULL;
670
671     if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS) {
672 #ifdef WIN32_VSS
673        /* will append \\?\ at front itself */
674        cygwin_conv_to_win32_path(path, tspec, max_len-4);
675 #else
676        /* allow path to be 32767 bytes */
677        tspec[0] = '\\';
678        tspec[1] = '\\';
679        tspec[2] = '?';
680        tspec[3] = '\\';
681        tspec[4] = 0;
682        cygwin_conv_to_win32_path(path, tspec+4, max_len-4);
683 #endif
684     } else {
685        cygwin_conv_to_win32_path(path, tspec, max_len);
686     }
687
688     bstrncat(tspec, "\\*", max_len);
689     rval->spec = tspec;
690
691     // convert to WCHAR
692     if (p_FindFirstFileW) {
693       POOLMEM* pwcBuf = get_pool_memory(PM_FNAME);;
694       UTF8_2_wchar(&pwcBuf,rval->spec);
695       rval->dirh = p_FindFirstFileW((LPCWSTR)pwcBuf, &rval->data_w);   
696
697       free_pool_memory(pwcBuf);
698
699       if (rval->dirh != INVALID_HANDLE_VALUE)
700         rval->valid_w = 1;
701     } else if (p_FindFirstFileA) {
702       rval->dirh = p_FindFirstFileA(rval->spec, &rval->data_a);
703       
704       if (rval->dirh != INVALID_HANDLE_VALUE)
705         rval->valid_a = 1;
706     } else goto err;
707
708
709     d_msg(__FILE__, __LINE__,
710           99, "opendir(%s)\n\tspec=%s,\n\tFindFirstFile returns %d\n",
711           path, rval->spec, rval->dirh);
712
713     rval->offset = 0;
714     if (rval->dirh == INVALID_HANDLE_VALUE)
715         goto err;
716
717     if (rval->valid_w)
718       d_msg(__FILE__, __LINE__,
719             99, "\tFirstFile=%s\n", rval->data_w.cFileName);
720
721     if (rval->valid_a)
722       d_msg(__FILE__, __LINE__,
723             99, "\tFirstFile=%s\n", rval->data_a.cFileName);
724
725     return (DIR *)rval;
726
727 err:
728     free((void *)rval->spec);
729     free(rval);
730     errno = b_errno_win32;
731     return NULL;
732 }
733
734 int
735 closedir(DIR *dirp)
736 {
737     _dir *dp = (_dir *)dirp;
738     FindClose(dp->dirh);
739     free((void *)dp->spec);
740     free((void *)dp);
741     return 0;
742 }
743
744 /*
745   typedef struct _WIN32_FIND_DATA {
746     DWORD dwFileAttributes;
747     FILETIME ftCreationTime;
748     FILETIME ftLastAccessTime;
749     FILETIME ftLastWriteTime;
750     DWORD nFileSizeHigh;
751     DWORD nFileSizeLow;
752     DWORD dwReserved0;
753     DWORD dwReserved1;
754     TCHAR cFileName[MAX_PATH];
755     TCHAR cAlternateFileName[14];
756 } WIN32_FIND_DATA, *PWIN32_FIND_DATA;
757 */
758
759 static int
760 copyin(struct dirent &dp, const char *fname)
761 {
762     dp.d_ino = 0;
763     dp.d_reclen = 0;
764     char *cp = dp.d_name;
765     while (*fname) {
766         *cp++ = *fname++;
767         dp.d_reclen++;
768     }
769         *cp = 0;
770     return dp.d_reclen;
771 }
772
773 int
774 readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
775 {
776     _dir *dp = (_dir *)dirp;
777     if (dp->valid_w || dp->valid_a) {
778       entry->d_off = dp->offset;
779                 
780       // copy unicode
781       if (dp->valid_w) {
782          char szBuf[MAX_PATH_UTF8];
783          wchar_2_UTF8(szBuf,dp->data_w.cFileName);
784          dp->offset += copyin(*entry, szBuf);
785       } else if (dp->valid_a) { // copy ansi (only 1 will be valid)
786          dp->offset += copyin(*entry, dp->data_a.cFileName);
787       }
788                 
789       *result = entry;              /* return entry address */
790       d_msg(__FILE__, __LINE__,
791             99, "readdir_r(%p, { d_name=\"%s\", d_reclen=%d, d_off=%d\n",
792             dirp, entry->d_name, entry->d_reclen, entry->d_off);
793     } else {
794 //      d_msg(__FILE__, __LINE__, 99, "readdir_r !valid\n");
795         errno = b_errno_win32;
796         return -1;
797     }
798
799     // get next file, try unicode first
800     if (p_FindNextFileW) 
801        dp->valid_w = p_FindNextFileW(dp->dirh, &dp->data_w);
802     else if (p_FindNextFileA)
803        dp->valid_a = p_FindNextFileA(dp->dirh, &dp->data_a);
804     else {
805        dp->valid_a = FALSE;
806        dp->valid_w = FALSE;
807     }
808
809     return 0;
810 }
811
812 /*
813  * Dotted IP address to network address
814  *
815  * Returns 1 if  OK
816  *         0 on error
817  */
818 int
819 inet_aton(const char *a, struct in_addr *inp)
820 {
821    const char *cp = a;
822    uint32_t acc = 0, tmp = 0;
823    int dotc = 0;
824
825    if (!isdigit(*cp)) {         /* first char must be digit */
826       return 0;                 /* error */
827    }
828    do {
829       if (isdigit(*cp)) {
830          tmp = (tmp * 10) + (*cp -'0');
831       } else if (*cp == '.' || *cp == 0) {
832          if (tmp > 255) {
833             return 0;           /* error */
834          }
835          acc = (acc << 8) + tmp;
836          dotc++;
837          tmp = 0;
838       } else {
839          return 0;              /* error */
840       }
841    } while (*cp++ != 0);
842    if (dotc != 4) {              /* want 3 .'s plus EOS */
843       return 0;                  /* error */
844    }
845    inp->s_addr = htonl(acc);     /* store addr in network format */
846    return 1;
847 }
848
849 int
850 nanosleep(const struct timespec *req, struct timespec *rem)
851 {
852     if (rem)
853         rem->tv_sec = rem->tv_nsec = 0;
854     Sleep((req->tv_sec * 1000) + (req->tv_nsec/100000));
855     return 0;
856 }
857
858 void
859 init_signals(void terminate(int sig))
860 {
861
862 }
863
864 void
865 init_stack_dump(void)
866 {
867
868 }
869
870
871 long
872 pathconf(const char *path, int name)
873 {
874     switch(name) {
875     case _PC_PATH_MAX :
876         if (strncmp(path, "\\\\?\\", 4) == 0)
877             return 32767;
878     case _PC_NAME_MAX :
879         return 255;
880     }
881     errno = ENOSYS;                                                         
882     return -1;
883 }
884
885 int
886 WSA_Init(void)
887 {
888     WORD wVersionRequested = MAKEWORD( 1, 1);
889     WSADATA wsaData;
890
891     int err = WSAStartup(wVersionRequested, &wsaData);
892
893
894     if (err != 0) {
895         printf("Can not start Windows Sockets\n");
896         errno = ENOSYS;
897         return -1;
898     }
899
900     return 0;
901 }
902
903
904 int
905 win32_chdir(const char *dir)
906 {
907    if (p_SetCurrentDirectoryW) {
908       POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
909       UTF8_2_wchar(&pwszBuf, dir);
910
911       BOOL b=p_SetCurrentDirectoryW((LPCWSTR)pwszBuf);
912       free_pool_memory(pwszBuf);
913
914       if (!b) {
915          errno = b_errno_win32;
916          return -1;
917       }
918    }
919    else if (p_SetCurrentDirectoryA) {
920       if (0 == p_SetCurrentDirectoryA(dir)) {
921          errno = b_errno_win32;
922          return -1;
923       }
924    }
925    else return -1;
926    
927    return 0;
928 }
929
930 int
931 win32_mkdir(const char *dir)
932 {
933    if (p_wmkdir){
934       POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
935       UTF8_2_wchar(&pwszBuf, dir);
936
937       int n=p_wmkdir((LPCWSTR)pwszBuf);
938       free_pool_memory(pwszBuf);      
939       return n;
940    }
941
942    return _mkdir(dir);        
943 }
944
945
946 char *
947 win32_getcwd(char *buf, int maxlen)
948 {
949    int n=0;
950
951    if (p_GetCurrentDirectoryW) {
952       POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
953       pwszBuf = check_pool_memory_size (pwszBuf, maxlen*sizeof(WCHAR));
954
955       n = p_GetCurrentDirectoryW(maxlen, (LPWSTR) pwszBuf);
956       n = wchar_2_UTF8 (buf, (WCHAR*)pwszBuf, maxlen)-1;
957       free_pool_memory(pwszBuf);
958
959    } else if (p_GetCurrentDirectoryA)
960       n = p_GetCurrentDirectoryA(maxlen, buf);
961
962    if (n == 0 || n > maxlen) return NULL;
963
964    if (n+1 > maxlen) return NULL;
965    if (n != 3) {
966        buf[n] = '\\';
967        buf[n+1] = 0;
968    }
969    return buf;
970 }
971
972 int 
973 win32_fputs(const char *string, FILE *stream)
974 {
975    /* we use WriteConsoleA / WriteConsoleA
976       so we can be sure that unicode support works on win32.
977       with fallback if something fails
978    */   
979
980    HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
981    if (hOut && (hOut != INVALID_HANDLE_VALUE) && p_WideCharToMultiByte && 
982        p_MultiByteToWideChar && (stream == stdout)) {
983       
984       POOLMEM* pwszBuf = get_pool_memory(PM_MESSAGE);
985       
986       DWORD dwCharsWritten;
987       DWORD dwChars;
988          
989       dwChars = UTF8_2_wchar(&pwszBuf, string);
990
991       /* try WriteConsoleW */
992       if (WriteConsoleW (hOut, pwszBuf, dwChars-1, &dwCharsWritten, NULL)) {
993          free_pool_memory(pwszBuf);
994          return dwCharsWritten;   
995       }
996       
997       /* convert to local codepage and try WriteConsoleA */      
998       POOLMEM* pszBuf = get_pool_memory(PM_MESSAGE);         
999       pszBuf = check_pool_memory_size(pszBuf, dwChars+1);
1000
1001       dwChars = p_WideCharToMultiByte(GetConsoleOutputCP(),0,(LPCWSTR) pwszBuf,-1,pszBuf,dwChars,NULL,NULL);      
1002       free_pool_memory(pwszBuf);
1003
1004       if (WriteConsoleA (hOut, pszBuf, dwChars-1, &dwCharsWritten, NULL)) {
1005          free_pool_memory(pszBuf);
1006          return dwCharsWritten;   
1007       }
1008    }
1009
1010    return fputs(string, stream);
1011 }
1012
1013 char*
1014 win32_cgets (char* buffer, int len)
1015 {
1016    /* we use console ReadConsoleA / ReadConsoleW to be able to read unicode
1017       from the win32 console and fallback if seomething fails */
1018
1019    HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
1020    if (hIn && (hIn != INVALID_HANDLE_VALUE) && p_WideCharToMultiByte && p_MultiByteToWideChar) {            
1021       DWORD dwRead;
1022       WCHAR wszBuf[1024];
1023       char  szBuf[1024];    
1024
1025       /* nt and unicode conversion */
1026       if (ReadConsoleW (hIn, wszBuf, 1024, &dwRead, NULL)) {
1027
1028          /* null terminate at end */                
1029          if (wszBuf[dwRead-1] == L'\n') {
1030             wszBuf[dwRead-1] = L'\0';
1031             dwRead --;
1032          }
1033
1034          if (wszBuf[dwRead-1] == L'\r') {
1035             wszBuf[dwRead-1] = L'\0';
1036             dwRead --;
1037          }
1038          
1039          wchar_2_UTF8(buffer, wszBuf, len);
1040          return buffer;
1041       }    
1042       
1043       /* win 9x and unicode conversion */
1044       if (ReadConsoleA (hIn, szBuf, 1024, &dwRead, NULL)) {
1045
1046          /* null terminate at end */                
1047          if (szBuf[dwRead-1] == L'\n') {
1048             szBuf[dwRead-1] = L'\0';
1049             dwRead --;
1050          }
1051
1052          if (szBuf[dwRead-1] == L'\r') {
1053             szBuf[dwRead-1] = L'\0';
1054             dwRead --;
1055          }
1056
1057          /* convert from ansii to WCHAR */
1058          p_MultiByteToWideChar(GetConsoleCP(), 0, szBuf, -1, wszBuf,1024);
1059          /* convert from WCHAR to UTF-8 */
1060          if (wchar_2_UTF8(buffer, wszBuf, len))
1061             return buffer;         
1062       }
1063    }
1064
1065    /* fallback */
1066    if (fgets(buffer, len, stdin)) 
1067       return buffer;   
1068    else
1069       return NULL;
1070 }
1071
1072 int
1073 win32_unlink(const char *filename)
1074 {
1075    int nRetCode;
1076    if (p_wunlink) {
1077       POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);      
1078       UTF8_2_wchar(&pwszBuf, filename);
1079       nRetCode = _wunlink((LPCWSTR) pwszBuf);
1080       free_pool_memory(pwszBuf);
1081    } else {
1082       nRetCode = _unlink(filename);
1083    }
1084    return nRetCode;
1085 }
1086
1087
1088 #include "mswinver.h"
1089
1090 char WIN_VERSION_LONG[64];
1091 char WIN_VERSION[32];
1092
1093 class winver {
1094 public:
1095     winver(void);
1096 };
1097
1098 static winver INIT;                     // cause constructor to be called before main()
1099
1100 #include "bacula.h"
1101 #include "jcr.h"
1102
1103 winver::winver(void)
1104 {
1105     const char *version = "";
1106     const char *platform = "";
1107     OSVERSIONINFO osvinfo;
1108     osvinfo.dwOSVersionInfoSize = sizeof(osvinfo);
1109
1110     // Get the current OS version
1111     if (!GetVersionEx(&osvinfo)) {
1112         version = "Unknown";
1113         platform = "Unknown";
1114     }
1115     else
1116         switch (_mkversion(osvinfo.dwPlatformId, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion))
1117         {
1118         case MS_WINDOWS_95: (version =  "Windows 95"); break;
1119         case MS_WINDOWS_98: (version =  "Windows 98"); break;
1120         case MS_WINDOWS_ME: (version =  "Windows ME"); break;
1121         case MS_WINDOWS_NT4:(version =  "Windows NT 4.0"); platform = "NT"; break;
1122         case MS_WINDOWS_2K: (version =  "Windows 2000");platform = "NT"; break;
1123         case MS_WINDOWS_XP: (version =  "Windows XP");platform = "NT"; break;
1124         case MS_WINDOWS_S2003: (version =  "Windows Server 2003");platform = "NT"; break;
1125         default: version = "Windows ??"; break;
1126         }
1127
1128     bstrncpy(WIN_VERSION_LONG, version, sizeof(WIN_VERSION_LONG));
1129     snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %d.%d.%d",
1130              platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
1131
1132 #if 0
1133     HANDLE h = CreateFile("G:\\foobar", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
1134     CloseHandle(h);
1135 #endif
1136 #if 0
1137     BPIPE *b = open_bpipe("ls -l", 10, "r");
1138     char buf[1024];
1139     while (!feof(b->rfd)) {
1140         fgets(buf, sizeof(buf), b->rfd);
1141     }
1142     close_bpipe(b);
1143 #endif
1144 }
1145
1146 BOOL CreateChildProcess(VOID);
1147 VOID WriteToPipe(VOID);
1148 VOID ReadFromPipe(VOID);
1149 VOID ErrorExit(LPCSTR);
1150 VOID ErrMsg(LPTSTR, BOOL);
1151
1152 /**
1153  * Check for a quoted path,  if an absolute path name is given and it contains
1154  * spaces it will need to be quoted.  i.e.  "c:/Program Files/foo/bar.exe"
1155  * CreateProcess() says the best way to ensure proper results with executables
1156  * with spaces in path or filename is to quote the string.
1157  */
1158 const char *
1159 getArgv0(const char *cmdline)
1160 {
1161
1162     int inquote = 0;
1163     for (const char *cp = cmdline; *cp; cp++)
1164     {
1165         if (*cp == '"') {
1166             inquote = !inquote;
1167         }
1168         if (!inquote && isspace(*cp))
1169             break;
1170     }
1171
1172         
1173     int len = cp - cmdline;
1174     char *rval = (char *)malloc(len+1);
1175
1176     cp = cmdline;
1177     char *rp = rval;
1178     
1179     while (len--)
1180         *rp++ = *cp++;
1181
1182     *rp = 0;
1183     return rval;
1184 }
1185
1186
1187 /**
1188  * OK, so it would seem CreateProcess only handles true executables:
1189  *  .com or .exe files.
1190  * So test to see whether we're getting a .bat file and if so grab
1191  * $COMSPEC value and pass batch file to it.
1192  */
1193 HANDLE
1194 CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err)
1195 {
1196     PROCESS_INFORMATION piProcInfo;
1197     STARTUPINFOA siStartInfo;
1198     BOOL bFuncRetn = FALSE;
1199
1200     // Set up members of the PROCESS_INFORMATION structure.
1201
1202     ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
1203
1204     // Set up members of the STARTUPINFO structure.
1205
1206     ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
1207     siStartInfo.cb = sizeof(STARTUPINFO);
1208     // setup new process to use supplied handles for stdin,stdout,stderr
1209     // if supplied handles are not used the send a copy of our STD_HANDLE
1210     // as appropriate
1211     siStartInfo.dwFlags = STARTF_USESTDHANDLES;
1212
1213     if (in != INVALID_HANDLE_VALUE)
1214         siStartInfo.hStdInput = in;
1215     else
1216         siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1217
1218     if (out != INVALID_HANDLE_VALUE)
1219         siStartInfo.hStdOutput = out;
1220     else
1221         siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1222     if (err != INVALID_HANDLE_VALUE)
1223         siStartInfo.hStdError = err;
1224     else
1225         siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1226     // Create the child process.
1227
1228     char exeFile[256];
1229
1230     const char *comspec = getenv("COMSPEC");
1231     
1232     if (comspec == NULL) // should never happen
1233         return INVALID_HANDLE_VALUE;
1234
1235     char *cmdLine = (char *)alloca(strlen(cmdline) + strlen(comspec) + 16);
1236     
1237     strcpy(exeFile, comspec);
1238     strcpy(cmdLine, comspec);
1239     strcat(cmdLine, " /c ");
1240     strcat(cmdLine, cmdline);
1241
1242     // try to execute program
1243     bFuncRetn = CreateProcessA(exeFile,
1244                               cmdLine, // command line
1245                               NULL, // process security attributes
1246                               NULL, // primary thread security attributes
1247                               TRUE, // handles are inherited
1248                               0, // creation flags
1249                               NULL, // use parent's environment
1250                               NULL, // use parent's current directory
1251                               &siStartInfo, // STARTUPINFO pointer
1252                               &piProcInfo); // receives PROCESS_INFORMATION
1253
1254     if (bFuncRetn == 0) {
1255         ErrorExit("CreateProcess failed\n");
1256         const char *err = errorString();
1257         d_msg(__FILE__, __LINE__, 99,
1258               "CreateProcess(%s, %s, ...)=%s\n", exeFile, cmdLine, err);
1259         LocalFree((void *)err);
1260         return INVALID_HANDLE_VALUE;
1261     }
1262     // we don't need a handle on the process primary thread so we close
1263     // this now.
1264     CloseHandle(piProcInfo.hThread);
1265
1266     return piProcInfo.hProcess;
1267 }
1268
1269
1270 void
1271 ErrorExit (LPCSTR lpszMessage)
1272 {
1273     d_msg(__FILE__, __LINE__, 0, "%s", lpszMessage);
1274 }
1275
1276
1277 /*
1278 typedef struct s_bpipe {
1279    pid_t worker_pid;
1280    time_t worker_stime;
1281    int wait;
1282    btimer_t *timer_id;
1283    FILE *rfd;
1284    FILE *wfd;
1285 } BPIPE;
1286 */
1287
1288 static void
1289 CloseIfValid(HANDLE handle)
1290 {
1291     if (handle != INVALID_HANDLE_VALUE)
1292         CloseHandle(handle);
1293 }
1294
1295 #ifndef HAVE_MINGW
1296 BPIPE *
1297 open_bpipe(char *prog, int wait, const char *mode)
1298 {
1299     HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup,
1300         hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup,
1301         hInputFile;
1302
1303     SECURITY_ATTRIBUTES saAttr;
1304
1305     BOOL fSuccess;
1306
1307     hChildStdinRd = hChildStdinWr = hChildStdinWrDup =
1308         hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup =
1309         hInputFile = INVALID_HANDLE_VALUE;
1310
1311     BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
1312     memset((void *)bpipe, 0, sizeof(BPIPE));
1313
1314     int mode_read = (mode[0] == 'r');
1315     int mode_write = (mode[0] == 'w' || mode[1] == 'w');
1316
1317
1318     // Set the bInheritHandle flag so pipe handles are inherited.
1319
1320     saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1321     saAttr.bInheritHandle = TRUE;
1322     saAttr.lpSecurityDescriptor = NULL;
1323
1324     if (mode_read) {
1325
1326         // Create a pipe for the child process's STDOUT.
1327         if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
1328             ErrorExit("Stdout pipe creation failed\n");
1329             goto cleanup;
1330         }
1331         // Create noninheritable read handle and close the inheritable read
1332         // handle.
1333
1334         fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
1335                                    GetCurrentProcess(), &hChildStdoutRdDup , 0,
1336                                    FALSE,
1337                                    DUPLICATE_SAME_ACCESS);
1338         if ( !fSuccess ) {
1339             ErrorExit("DuplicateHandle failed");
1340             goto cleanup;
1341         }
1342
1343         CloseHandle(hChildStdoutRd);
1344         hChildStdoutRd = INVALID_HANDLE_VALUE;
1345     }
1346
1347     if (mode_write) {
1348
1349         // Create a pipe for the child process's STDIN.
1350
1351         if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
1352             ErrorExit("Stdin pipe creation failed\n");
1353             goto cleanup;
1354         }
1355
1356         // Duplicate the write handle to the pipe so it is not inherited.
1357         fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
1358                                    GetCurrentProcess(), &hChildStdinWrDup,
1359                                    0,
1360                                    FALSE,                  // not inherited
1361                                    DUPLICATE_SAME_ACCESS);
1362         if (!fSuccess) {
1363             ErrorExit("DuplicateHandle failed");
1364             goto cleanup;
1365         }
1366
1367         CloseHandle(hChildStdinWr);
1368         hChildStdinWr = INVALID_HANDLE_VALUE;
1369     }
1370     // spawn program with redirected handles as appropriate
1371     bpipe->worker_pid = (pid_t)
1372         CreateChildProcess(prog,             // commandline
1373                            hChildStdinRd,    // stdin HANDLE
1374                            hChildStdoutWr,   // stdout HANDLE
1375                            hChildStdoutWr);  // stderr HANDLE
1376
1377     if ((HANDLE) bpipe->worker_pid == INVALID_HANDLE_VALUE)
1378         goto cleanup;
1379
1380     bpipe->wait = wait;
1381     bpipe->worker_stime = time(NULL);
1382
1383     if (mode_read) {
1384         CloseHandle(hChildStdoutWr); // close our write side so when
1385                                      // process terminates we can
1386                                      // detect eof.
1387         // ugly but convert WIN32 HANDLE to FILE*
1388         int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
1389         if (rfd >= 0) {
1390            bpipe->rfd = _fdopen(rfd, "r");
1391         }
1392     }
1393     if (mode_write) {
1394         CloseHandle(hChildStdinRd); // close our read side so as not
1395                                     // to interfre with child's copy
1396         // ugly but convert WIN32 HANDLE to FILE*
1397         int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
1398         if (wfd >= 0) {
1399            bpipe->wfd = _fdopen(wfd, "w");
1400         }
1401     }
1402
1403     if (wait > 0) {
1404         bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
1405     }
1406
1407     return bpipe;
1408
1409 cleanup:
1410
1411     CloseIfValid(hChildStdoutRd);
1412     CloseIfValid(hChildStdoutRdDup);
1413     CloseIfValid(hChildStdinWr);
1414     CloseIfValid(hChildStdinWrDup);
1415
1416     free((void *) bpipe);
1417     errno = b_errno_win32;            /* do GetLastError() for error code */
1418     return NULL;
1419 }
1420
1421 #endif //HAVE_MINGW
1422
1423 int
1424 kill(int pid, int signal)
1425 {
1426    int rval = 0;
1427    if (!TerminateProcess((HANDLE)pid, (UINT) signal)) {
1428       rval = -1;
1429       errno = b_errno_win32;
1430    }
1431    CloseHandle((HANDLE)pid);
1432    return rval;
1433 }
1434
1435 #ifndef HAVE_MINGW
1436
1437 int
1438 close_bpipe(BPIPE *bpipe)
1439 {
1440    int rval = 0;
1441    int32_t remaining_wait = bpipe->wait;
1442
1443    if (remaining_wait == 0) {         /* wait indefinitely */
1444       remaining_wait = INT32_MAX;
1445    }
1446    for ( ;; ) {
1447       DWORD exitCode;
1448       if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode)) {
1449          const char *err = errorString();
1450          rval = b_errno_win32;
1451          d_msg(__FILE__, __LINE__, 0,
1452                "GetExitCode error %s\n", err);
1453          LocalFree((void *)err);
1454          break;
1455       }
1456       if (exitCode == STILL_ACTIVE) {
1457          if (remaining_wait <= 0) {
1458             rval = ETIME;             /* timed out */
1459             break;
1460          }
1461          bmicrosleep(1, 0);           /* wait one second */
1462          remaining_wait--;
1463       } else if (exitCode != 0) {
1464          /* Truncate exit code as it doesn't seem to be correct */
1465          rval = (exitCode & 0xFF) | b_errno_exit;
1466          break;
1467       } else {
1468          break;                       /* Shouldn't get here */
1469       }
1470    }
1471
1472    if (bpipe->timer_id) {
1473        stop_child_timer(bpipe->timer_id);
1474    }
1475    if (bpipe->rfd) fclose(bpipe->rfd);
1476    if (bpipe->wfd) fclose(bpipe->wfd);
1477    free((void *)bpipe);
1478    return rval;
1479 }
1480
1481 int
1482 close_wpipe(BPIPE *bpipe)
1483 {
1484     int stat = 1;
1485
1486     if (bpipe->wfd) {
1487         fflush(bpipe->wfd);
1488         if (fclose(bpipe->wfd) != 0) {
1489             stat = 0;
1490         }
1491         bpipe->wfd = NULL;
1492     }
1493     return stat;
1494 }
1495
1496 #include "findlib/find.h"
1497
1498 int
1499 utime(const char *fname, struct utimbuf *times)
1500 {
1501     FILETIME acc, mod;
1502     char tmpbuf[1024];
1503
1504     cygwin_conv_to_win32_path(fname, tmpbuf, 1024);
1505
1506     cvt_utime_to_ftime(times->actime, acc);
1507     cvt_utime_to_ftime(times->modtime, mod);
1508
1509     HANDLE h = INVALID_HANDLE_VALUE;
1510
1511     if (p_CreateFileW) {
1512       POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);
1513       UTF8_2_wchar(&pwszBuf, tmpbuf);
1514
1515       h = p_CreateFileW((LPCWSTR) pwszBuf,
1516                         FILE_WRITE_ATTRIBUTES,
1517                         FILE_SHARE_WRITE,
1518                         NULL,
1519                         OPEN_EXISTING,
1520                         0,
1521                         NULL);
1522      
1523       free_pool_memory(pwszBuf);
1524     } else if (p_CreateFileA) {
1525       h = p_CreateFileA(tmpbuf,
1526                         FILE_WRITE_ATTRIBUTES,
1527                         FILE_SHARE_WRITE,
1528                         NULL,
1529                         OPEN_EXISTING,
1530                         0,
1531                         NULL);
1532     }
1533
1534     if (h == INVALID_HANDLE_VALUE) {
1535         const char *err = errorString();
1536         d_msg(__FILE__, __LINE__, 99,
1537               "Cannot open file \"%s\" for utime(): ERR=%s", tmpbuf, err);
1538         LocalFree((void *)err);
1539         errno = b_errno_win32;
1540         return -1;
1541     }
1542
1543     int rval = SetFileTime(h, NULL, &acc, &mod) ? 0 : -1;
1544     CloseHandle(h);
1545     if (rval == -1) {
1546        errno = b_errno_win32;
1547     }
1548     return rval;
1549 }
1550
1551 #if USE_WIN32_COMPAT_IO
1552
1553 int
1554 open(const char *file, int flags, int mode)
1555 {
1556    if (p_wopen) {
1557       POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);      
1558       UTF8_2_wchar(&pwszBuf, file);
1559
1560       int nRet = p_wopen((LPCWSTR) pwszBuf, flags|_O_BINARY, mode);
1561       free_pool_memory(pwszBuf);
1562
1563       return nRet;
1564    }
1565
1566    return _open(file, flags|_O_BINARY, mode);
1567 }
1568
1569 /*
1570  * Note, this works only for a file. If you want
1571  *   to close a socket, use closesocket(). 
1572  *   Bacula has been modified in src/lib/bnet.c
1573  *   to use closesocket().
1574  */
1575 int
1576 close(int fd)
1577 {
1578     return _close(fd);
1579 }
1580
1581 #ifndef HAVE_WXCONSOLE
1582 ssize_t
1583 read(int fd, void *buf, ssize_t len)
1584 {
1585     return _read(fd, buf, (size_t)len);
1586 }
1587
1588 ssize_t
1589 write(int fd, const void *buf, ssize_t len)
1590 {
1591     return _write(fd, buf, (size_t)len);
1592 }
1593 #endif
1594
1595
1596 off_t
1597 lseek(int fd, off_t offset, int whence)
1598 {
1599     return _lseeki64(fd, offset, whence);
1600 }
1601
1602 int
1603 dup2(int fd1, int fd2)
1604 {
1605     return _dup2(fd1, fd2);
1606 }
1607 #else
1608 int
1609 open(const char *file, int flags, int mode)
1610 {
1611     DWORD access = 0;
1612     DWORD shareMode = 0;
1613     DWORD create = 0;
1614     DWORD msflags = 0;
1615     HANDLE foo = INVALID_HANDLE_VALUE;
1616     const char *remap = file;
1617
1618     if (flags & O_WRONLY) access = GENERIC_WRITE;
1619     else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
1620     else access = GENERIC_READ;
1621
1622     if (flags & O_CREAT) create = CREATE_NEW;
1623     else create = OPEN_EXISTING;
1624
1625     if (flags & O_TRUNC) create = TRUNCATE_EXISTING;
1626
1627     if (!(flags & O_EXCL))
1628         shareMode = FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE;
1629
1630     if (flags & O_APPEND) {
1631         printf("open...APPEND not implemented yet.");
1632         exit(-1);
1633     }
1634
1635     if (p_CreateFileW) {
1636        POOLMEM* pwszBuf = get_pool_memory(PM_FNAME);       
1637        UTF8_2_wchar(pwszBuf, file);
1638
1639        foo = p_CreateFileW((LPCWSTR) pwszBuf, access, shareMode, NULL, create, msflags, NULL);
1640        free_pool_memory(pwszBuf);
1641     }
1642     else if (p_CreateFileA)
1643        foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
1644
1645     if (INVALID_HANDLE_VALUE == foo) {
1646         errno = b_errno_win32;
1647         return(int) -1;
1648     }
1649     return (int)foo;
1650
1651 }
1652
1653
1654 int
1655 close(int fd)
1656 {
1657     if (!CloseHandle((HANDLE)fd)) {
1658         errno = b_errno_win32;
1659         return -1;
1660     }
1661
1662     return 0;
1663 }
1664
1665 ssize_t
1666 write(int fd, const void *data, ssize_t len)
1667 {
1668     BOOL status;
1669     DWORD bwrite;
1670     status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
1671     if (status) return bwrite;
1672     errno = b_errno_win32;
1673     return -1;
1674 }
1675
1676
1677 ssize_t
1678 read(int fd, void *data, ssize_t len)
1679 {
1680     BOOL status;
1681     DWORD bread;
1682
1683     status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
1684     if (status) return bread;
1685     errno = b_errno_win32;
1686     return -1;
1687 }
1688
1689 off_t
1690 lseek(int fd, off_t offset, int whence)
1691 {
1692     DWORD method = 0;
1693     DWORD val;
1694     switch (whence) {
1695     case SEEK_SET :
1696         method = FILE_BEGIN;
1697         break;
1698     case SEEK_CUR:
1699         method = FILE_CURRENT;
1700         break;
1701     case SEEK_END:
1702         method = FILE_END;
1703         break;
1704     default:
1705         errno = EINVAL;
1706         return -1;
1707     }
1708
1709     if ((val=SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method)) == INVALID_SET_FILE_POINTER) {
1710        errno = b_errno_win32;
1711        return -1;
1712     }
1713     /* ***FIXME*** I doubt this works right */
1714     return val;
1715 }
1716
1717 int
1718 dup2(int, int)
1719 {
1720     errno = ENOSYS;
1721     return -1;
1722 }
1723
1724
1725 #endif
1726
1727 #endif //HAVE_MINGW
1728
1729 #ifdef HAVE_MINGW
1730 /* syslog function, added by Nicolas Boichat */
1731 void closelog() {}
1732 #endif //HAVE_MINGW