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