]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/win32/compat/compat.cpp
ebdf82ba8244aac5c48c3208f159273b445a9630
[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 (C)2004 Raider Solutions, Inc
6 // 
7 //   This program is free software; you can redistribute it and/or
8 //   modify it under the terms of the GNU General Public License as
9 //   published by the Free Software Foundation; either version 2 of
10 //   the License, or (at your option) any later version.
11 //
12 //   This program is distributed in the hope that it will be useful,
13 //   but WITHOUT ANY WARRANTY; without even the implied warranty of
14 //   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 //   General Public License for more details.
16 //
17 //   You should have received a copy of the GNU General Public
18 //   License along with this program; if not, write to the Free
19 //   Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20 //   MA 02111-1307, USA.
21 //
22 // Author          : Christopher S. Hull
23 // Created On      : Sat Jan 31 15:55:00 2004
24 // Last Modified By: Christopher S. Hull
25 // Last Modified On: Mon Feb  9 17:22:31 2004
26 // Update Count    : 591
27 // $Id$
28
29 #include <stdio.h>
30
31 #include "compat.h"
32 #include "pthread.h"
33
34 extern void d_msg(const char *file, int line, int level, const char *fmt,...);
35 extern DWORD   g_platform_id;
36
37
38 extern "C" void
39 cygwin_conv_to_win32_path(const char *name, char *win32_name)
40 {
41     const char *fname = name;
42     while (*name) {
43         /* Check for Unix separator and convert to Win32 */
44         if (*name == '/') {
45             *win32_name++ = '\\';     /* convert char */
46         /* If Win32 separated that is "quoted", remove quote */
47         } else if (*name == '\\' && name[1] == '\\') {
48             *win32_name++ = '\\';
49             name++;                   /* skip first \ */
50         } else {
51             *win32_name++ = *name;    /* copy character */
52         }
53         name++;
54     }
55     /* Strip any trailing slash, if we stored something */
56     if (*fname != 0 && win32_name[-1] == '\\') {
57         win32_name[-1] = 0;
58     } else {
59         *win32_name = 0;
60     }
61 }
62
63
64 int
65 open(const char *file, int flags, int mode)
66 {
67     DWORD access = 0;
68     DWORD shareMode = 0;
69     DWORD create = 0;
70     DWORD msflags = 0;
71     HANDLE foo;
72     const char *remap = file;
73
74     if (flags & O_WRONLY) access = GENERIC_WRITE;
75     else if (flags & O_RDWR) access = GENERIC_READ|GENERIC_WRITE;
76     else access = GENERIC_READ;
77     
78     if (flags & O_CREAT) create = CREATE_NEW;
79     else create = OPEN_EXISTING;
80     
81     if (flags & O_TRUNC) create = TRUNCATE_EXISTING;
82     
83     if (!(flags & O_EXCL))
84         shareMode = FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE;
85     
86     if (flags & O_APPEND)
87     {
88         printf("open...APPEND not implemented yet.");
89         exit(-1);
90     }
91     
92     foo = CreateFile(file, access, shareMode, NULL, create, msflags, NULL);
93     if (INVALID_HANDLE_VALUE == foo)
94         return(int) -1;
95
96     return (int)foo;
97
98 }
99
100
101 int
102 close(int fd)
103 {
104     if (!CloseHandle((HANDLE)fd))
105         return -1;
106
107     return 0;
108 }
109
110 int
111 write(int fd, const void *data, int32_t len)
112 {
113     BOOL status;
114     DWORD bwrite;
115     status = WriteFile((HANDLE)fd, data, len, &bwrite, NULL);
116     if (status) return bwrite;
117     return -1;
118 }
119
120
121 int
122 read(int fd, void *data, int32_t len)
123 {
124     BOOL status;
125     DWORD bread;
126
127     status = ReadFile((HANDLE)fd, data, len, &bread, NULL);
128     if (status) return bread;
129
130     return -1;
131 }
132
133 int
134 umask(int)
135 {
136     return 0;
137 }
138
139 int
140 chmod(const char *, mode_t)
141 {
142     return 0;
143 }
144
145 int
146 chown(const char *k, uid_t, gid_t)
147 {
148     return 0;
149 }
150
151 int
152 lchown(const char *k, uid_t, gid_t)
153 {
154     return 0;
155 }
156
157 int
158 utime(const char *, struct utimbuf *)
159 {
160     return -1;
161 }
162
163
164 long int
165 random(void)
166 {
167     return rand();
168 }
169
170 void
171 srandom(unsigned int seed)
172 {
173     srand(seed);
174 }
175 // /////////////////////////////////////////////////////////////////
176 // convert from Windows concept of time to Unix concept of time
177 // /////////////////////////////////////////////////////////////////
178 time_t
179 cvt(const FILETIME &time)
180 {
181     uint64_t mstime = time.dwHighDateTime;
182     mstime <<= 32;
183     mstime |= time.dwLowDateTime;
184
185     mstime /= 10000000;         // convert to seconds.
186     mstime -= 3234336I64*3600I64; // difference between jan 1, 1601
187                                   // and jan, 1 1970
188
189     return (time_t) (mstime & 0xffffffff);
190 }
191
192 static const char *
193 errorString(void)
194 {
195     LPVOID lpMsgBuf;
196
197     FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
198                   FORMAT_MESSAGE_FROM_SYSTEM |
199                   FORMAT_MESSAGE_IGNORE_INSERTS,
200                   NULL,
201                   GetLastError(),
202                   MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default lang
203                   (LPTSTR) &lpMsgBuf,
204                   0,
205                   NULL);
206
207     return (const char *) lpMsgBuf;
208 }
209
210 static int
211 statDir(const char *file, struct stat *sb)
212 {
213     WIN32_FIND_DATA info;       // window's file info
214     sb->st_mode |= S_IFDIR;
215
216     if (file[1] == ':' && file[2] == 0)
217     {
218         d_msg(__FILE__, __LINE__, 99, "faking ROOT attrs(%s).\n", file);
219         sb->st_mode |= S_IREAD|S_IEXEC|S_IWRITE;
220         time(&sb->st_ctime);
221         time(&sb->st_mtime);
222         time(&sb->st_atime);
223         return 0;
224     }
225     HANDLE h = FindFirstFile(file, &info);
226
227     if (h == INVALID_HANDLE_VALUE) {
228         const char *err = errorString();
229         d_msg(__FILE__, __LINE__, 99, "FindFirstFile(%s):%s\n", file, err);
230         LocalFree((void *)err);
231         errno = GetLastError();
232         return -1;
233     }
234
235     sb->st_mode |= (S_IREAD | S_IEXEC);
236     if (!(info.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
237         sb->st_mode |= S_IWRITE;
238     
239     if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
240         sb->st_mode |= S_IRGRP;
241     if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
242         sb->st_mode |= S_IROTH;
243     sb->st_size = info.nFileSizeHigh;
244     sb->st_size <<= 32;
245     sb->st_size |= info.nFileSizeLow;
246     sb->st_blksize = 4096;
247     sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
248     sb->st_atime = cvt(info.ftLastAccessTime);
249     sb->st_mtime = cvt(info.ftLastWriteTime);
250     sb->st_ctime = cvt(info.ftCreationTime);
251
252     return 0;
253 }
254
255 static int
256 stat2(const char *file, struct stat *sb)
257 {
258     BY_HANDLE_FILE_INFORMATION info;
259     HANDLE h;
260     int rval = 0;
261     char tmpbuf[1024];
262     cygwin_conv_to_win32_path(file, tmpbuf);
263
264     DWORD attr = GetFileAttributes(tmpbuf);
265
266     if (attr == -1) {
267         const char *err = errorString();
268         d_msg(__FILE__, __LINE__, 99,
269               "GetFileAttrubtes(%s): %s\n", tmpbuf, err);
270         LocalFree((void *)err);
271         errno = GetLastError();
272         return -1;
273     }
274     
275     if (attr & FILE_ATTRIBUTE_DIRECTORY) 
276         return statDir(tmpbuf, sb);
277
278     sb->st_mode |= S_IFREG;
279     
280     h = CreateFile(tmpbuf, GENERIC_READ,
281                    FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
282
283     if (h == INVALID_HANDLE_VALUE) {
284         const char *err = errorString();
285         d_msg(__FILE__, __LINE__, 99,
286               "Cannot open file for stat (%s):%s\n", tmpbuf, err);
287         LocalFree((void *)err);
288         rval = -1;
289         errno = GetLastError();
290         goto error;
291     }
292     
293     if (!GetFileInformationByHandle(h, &info)) {
294         const char *err = errorString();
295         d_msg(__FILE__, __LINE__, 99,
296               "GetfileInformationByHandle(%s): %s\n", tmpbuf, err);
297         LocalFree((void *)err);
298         rval = -1;
299         errno = GetLastError();
300         goto error;
301     }
302     
303     sb->st_dev = info.dwVolumeSerialNumber;
304     sb->st_ino = info.nFileIndexHigh;
305     sb->st_ino <<= 32;
306     sb->st_ino |= info.nFileIndexLow;
307     sb->st_nlink = (short)info.nNumberOfLinks;
308     sb->st_mode |= (S_IREAD | S_IEXEC);
309     if (!(info.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
310         sb->st_mode |= S_IWRITE;
311
312     if (info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
313         sb->st_mode |= S_IRGRP;
314     if (info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
315         sb->st_mode |= S_IROTH;
316     sb->st_size = info.nFileSizeHigh;
317     sb->st_size <<= 32;
318     sb->st_size |= info.nFileSizeLow;
319     sb->st_blksize = 4096;
320     sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
321     sb->st_atime = cvt(info.ftLastAccessTime);
322     sb->st_mtime = cvt(info.ftLastWriteTime);
323     sb->st_ctime = cvt(info.ftCreationTime);
324
325 error:
326     CloseHandle(h);
327     return rval;
328 }
329
330 int
331 stat(const char *file, struct stat *sb)
332 {
333     WIN32_FILE_ATTRIBUTE_DATA data;
334     errno = 0;
335
336     memset(sb, 0, sizeof(*sb));
337
338     if (g_platform_id == VER_PLATFORM_WIN32_WINDOWS)
339         return stat2(file, sb);
340
341     if (!GetFileAttributesEx(file, GetFileExInfoStandard, &data))
342         return stat2(file, sb);
343
344     if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
345         sb->st_mode |= S_IFDIR;
346     else
347         sb->st_mode |= S_IFREG;
348
349     sb->st_nlink = 1;
350     sb->st_mode |= (S_IREAD | S_IEXEC);
351     if (!(data.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
352         sb->st_mode |= S_IWRITE;
353
354     if (data.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
355         sb->st_mode |= S_IRGRP;
356     if (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
357         sb->st_mode |= S_IROTH;
358     sb->st_size = data.nFileSizeHigh;
359     sb->st_size <<= 32;
360     sb->st_size |= data.nFileSizeLow;
361     sb->st_blksize = 4096;
362     sb->st_blocks = (uint32_t)(sb->st_size + 4095)/4096;
363     sb->st_atime = cvt(data.ftLastAccessTime);
364     sb->st_mtime = cvt(data.ftLastWriteTime);
365     sb->st_ctime = cvt(data.ftCreationTime);
366     return 0;
367 }
368
369 int
370 lstat(const char *file, struct stat *sb)
371 {
372     return stat(file, sb);
373 }
374
375 void
376 sleep(int sec)
377 {
378     Sleep(sec * 1000);
379 }    
380
381 int
382 geteuid(void)
383 {
384     return 0;
385 }
386
387 int
388 execvp(const char *, char *[]) {
389     return -1;
390 }
391
392 int
393 dup2(int, int)
394 {
395     return -1;
396 }
397
398 int
399 fork(void)
400 {
401     return -1;
402 }
403
404 int
405 pipe(int[])
406 {
407     return -1;
408 }
409
410 int
411 waitpid(int, int*, int)
412 {
413     return -1;
414 }
415
416 int
417 readlink(const char *, char *, int)
418 {
419     return -1;
420 }
421
422 int
423 lseek(int fd, int offset, int whence)
424 {
425     DWORD method = 0;
426     switch (whence) {
427     case SEEK_SET :
428         method = FILE_BEGIN;
429         break;
430     case SEEK_CUR:
431         method = FILE_CURRENT;
432         break;
433     case SEEK_END:
434         method = FILE_END;
435         break;
436     default:
437         return -1;
438     }
439     
440     return SetFilePointer((HANDLE)fd, (DWORD)offset, NULL, method);
441 }
442
443 int
444 strcasecmp(const char *s1, const char *s2)
445 {
446     register int ch1, ch2;
447     
448     if (s1==s2)
449         return 0;       /* strings are equal if same object. */
450     else if (!s1)
451         return -1;
452     else if (!s2)
453         return 1;
454     do
455     {
456         ch1 = *s1;
457         ch2 = *s2;
458         s1++;
459         s2++;
460     } while (ch1 != 0 && tolower(ch1) == tolower(ch2));
461     
462   return(ch1 - ch2);
463 }
464
465 int
466 strncasecmp(const char *s1, const char *s2, int len)
467 {
468     register int ch1, ch2;
469     
470     if (s1==s2)
471         return 0;       /* strings are equal if same object. */
472     else if (!s1)
473         return -1;
474     else if (!s2)
475         return 1;
476     do
477     {
478         ch1 = *s1;
479         ch2 = *s2;
480         s1++;
481         s2++;
482     } while (len-- && ch1 != 0 && tolower(ch1) == tolower(ch2));
483     
484     return(ch1 - ch2);
485 }
486
487 int
488 gettimeofday(struct timeval *tv, struct timezone *)
489 {
490     SYSTEMTIME now;
491     FILETIME tmp;
492     GetSystemTime(&now);
493
494     if (tv == NULL) return -1;
495     if (!SystemTimeToFileTime(&now, &tmp)) return -1;
496
497     int64_t _100nsec = tmp.dwHighDateTime;
498     _100nsec <<= 32;
499     _100nsec |= tmp.dwLowDateTime;
500     _100nsec -= (3234336I64*3600I64 * 10000000I64);
501     tv->tv_sec =(long) (_100nsec / 10000000);
502     tv->tv_usec = (long) ((_100nsec % 10000000)/10);
503     return 0;
504     
505 }
506
507 int
508 syslog(int, const char *, const char *)
509 {
510     return 0;
511 }
512
513 struct passwd *
514 getpwuid(uid_t)
515 {
516     return NULL;
517 }
518
519 struct group *
520 getgrgid(uid_t)
521 {
522     return NULL;
523 }
524
525
526 // implement opendir/readdir/closedir on top of window's API
527 typedef struct _dir
528 {
529     WIN32_FIND_DATA data;       // window's file info
530     const char *spec;           // the directory we're traversing
531     HANDLE      dirh;           // the search handle
532     BOOL        valid;          // the info in data field is valid
533     UINT32      offset;         // pseudo offset for d_off
534 } _dir;
535
536 DIR *
537 opendir(const char *path)
538 {
539     int max_len = strlen(path) + 16;
540     _dir *rval = NULL;
541     if (path == NULL) return NULL;
542     
543     rval = (_dir *)malloc(sizeof(_dir));
544     if (rval == NULL) return NULL;
545     char *tspec = (char *)malloc(max_len);
546     if (tspec == NULL) goto err1;
547     
548     if (g_platform_id != VER_PLATFORM_WIN32_WINDOWS) {
549         // allow path to be 32767 bytes
550         tspec[0] = '\\';
551         tspec[1] = '\\';
552         tspec[2] = '?';
553         tspec[3] = '\\';
554         tspec[4] = 0;
555         cygwin_conv_to_win32_path(path, tspec+4); 
556     } else {
557         cygwin_conv_to_win32_path(path, tspec);
558     }
559     strncat(tspec, "\\*", max_len);
560     rval->spec = tspec;
561
562     rval->dirh = FindFirstFile(rval->spec, &rval->data);
563     d_msg(__FILE__, __LINE__,
564           99, "opendir(%s)\n\tspec=%s,\n\tFindFirstFile returns %d\n",
565           path, rval->spec, rval->dirh);
566
567     rval->offset = 0;
568     if (rval->dirh == INVALID_HANDLE_VALUE)
569         goto err;
570     rval->valid = 1;
571     d_msg(__FILE__, __LINE__,
572           99, "\tFirstFile=%s\n", rval->data.cFileName);
573     return (DIR *)rval;
574 err:
575     free((void *)rval->spec);
576 err1:
577     free(rval);
578     return NULL;
579 }
580     
581 int
582 closedir(DIR *dirp)
583 {
584     _dir *dp = (_dir *)dirp;
585     FindClose(dp->dirh);
586     free((void *)dp->spec);
587     free((void *)dp);
588     return 0;
589 }
590
591 /*
592   typedef struct _WIN32_FIND_DATA {
593     DWORD dwFileAttributes;
594     FILETIME ftCreationTime;
595     FILETIME ftLastAccessTime;
596     FILETIME ftLastWriteTime;
597     DWORD nFileSizeHigh;
598     DWORD nFileSizeLow;
599     DWORD dwReserved0;
600     DWORD dwReserved1;
601     TCHAR cFileName[MAX_PATH];
602     TCHAR cAlternateFileName[14];
603 } WIN32_FIND_DATA, *PWIN32_FIND_DATA;
604 */
605
606 static int
607 copyin(struct dirent &dp, const char *fname)
608 {
609     dp.d_ino = 0;
610     dp.d_reclen = 0;
611     char *cp = dp.d_name;
612     while (*fname) {
613         *cp++ = *fname++;
614         dp.d_reclen++;
615     }
616         *cp = 0;
617     return dp.d_reclen;
618 }
619 int
620 readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result)
621 {
622
623     _dir *dp = (_dir *)dirp;
624     if (dp->valid) {
625         entry->d_off = dp->offset;
626         dp->offset += copyin(*entry, dp->data.cFileName);
627         *result = entry;              /* return entry address */
628         d_msg(__FILE__, __LINE__,
629               99, "readdir_r(%p, { d_name=\"%s\", d_reclen=%d, d_off=%d\n",
630               dirp, entry->d_name, entry->d_reclen, entry->d_off);
631     } else {
632 //      d_msg(__FILE__, __LINE__, 99, "readdir_r !valid\n");
633         return -1;
634     }
635     dp->valid = FindNextFile(dp->dirh, &dp->data);
636     return 0;
637 }
638
639
640 int
641 inet_aton(const char *a, struct in_addr *inp)
642 {
643
644     const char *cp = a;
645     uint32_t acc = 0, tmp = 0;
646     int dotc = 0;
647     if (!isdigit(*a)) return 0;
648     while (*cp) {
649         if (isdigit(*cp))
650             tmp = (tmp * 10) + (*cp -'0');
651         else if (*cp == '.') {
652             if (tmp > 255) return 0;
653             acc = (acc << 8) + tmp;
654             dotc++;
655         }
656         else return 0;
657     }
658
659     if (dotc != 3) return 0;
660     inp->s_addr = acc;
661     return 1;
662 }
663
664 int
665 nanosleep(const struct timespec *req, struct timespec *rem)
666 {
667     if (rem)
668         rem->tv_sec = rem->tv_nsec = 0;
669     Sleep((req->tv_sec * 1000) + (req->tv_nsec/100000));
670     return 0;
671 }
672
673 void
674 init_signals(void terminate(int sig))
675 {
676
677 }
678
679 void
680 init_stack_dump(void)
681 {
682
683 }
684
685
686 long
687 pathconf(const char *path, int name)
688 {
689     switch(name) {
690     case _PC_PATH_MAX :
691         if (strncmp(path, "\\\\?\\", 4) == 0)
692             return 32767;
693     case _PC_NAME_MAX :
694         return 255;
695     }
696
697     return -1;
698 }
699
700 int
701 WSA_Init(void)
702 {
703     WORD wVersionRequested = MAKEWORD( 1, 1);
704     WSADATA wsaData;
705     
706     int err = WSAStartup(wVersionRequested, &wsaData);
707     
708     
709     if (err != 0)
710     {
711         printf("Can not start Windows Sockets\n");
712         return -1;
713     }
714
715     return 0;
716 }
717
718
719 int
720 win32_chdir(const char *dir)
721 {
722     if (0 == SetCurrentDirectory(dir)) return -1;
723     return 0;
724 }
725
726 char *
727 win32_getcwd(char *buf, int maxlen)
728 {
729    int n =  GetCurrentDirectory(maxlen, buf);
730
731    if (n == 0 || n > maxlen) return NULL;
732
733    if (n+1 > maxlen) return NULL;
734    if (n != 3) {
735        buf[n] = '\\';
736        buf[n+1] = 0;
737    }
738    
739    return buf;
740 }
741
742 #include "mswinver.h"
743
744 char WIN_VERSION_LONG[64];
745 char WIN_VERSION[32];
746
747 class winver {
748 public:
749     winver(void);
750 };
751
752 static winver INIT;                     // cause constructor to be called before main()
753
754 #include "bacula.h"
755 #include "jcr.h"
756
757 winver::winver(void)
758 {
759     const char *version = "";
760     const char *platform = "";
761     OSVERSIONINFO osvinfo;
762     osvinfo.dwOSVersionInfoSize = sizeof(osvinfo);
763
764     // Get the current OS version
765     if (!GetVersionEx(&osvinfo)) {
766         version = "Unknown";
767         platform = "Unknown";
768     }
769     else
770         switch (_mkversion(osvinfo.dwPlatformId, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion))
771         {
772         case MS_WINDOWS_95: (version =  "Windows 95"); break;
773         case MS_WINDOWS_98: (version =  "Windows 98"); break;
774         case MS_WINDOWS_ME: (version =  "Windows ME"); break;
775         case MS_WINDOWS_NT4:(version =  "Windows NT 4.0"); platform = "NT"; break;
776         case MS_WINDOWS_2K: (version =  "Windows 2000");platform = "NT"; break;
777         case MS_WINDOWS_XP: (version =  "Windows XP");platform = "NT"; break;
778         case MS_WINDOWS_S2003: (version =  "Windows Server 2003");platform = "NT"; break;
779         default: version = "Windows ??"; break;
780         }
781
782     bstrncpy(WIN_VERSION_LONG, version, sizeof(WIN_VERSION_LONG));
783     snprintf(WIN_VERSION, sizeof(WIN_VERSION), "%s %d.%d.%d",
784              platform, osvinfo.dwMajorVersion, osvinfo.dwMinorVersion, osvinfo.dwBuildNumber);
785
786 #if 0
787     BPIPE *b = open_bpipe("ls -l", 10, "r");
788     char buf[1024];
789     while (!feof(b->rfd)) {
790         fgets(buf, sizeof(buf), b->rfd);
791     }
792     close_bpipe(b);
793 #endif
794 }
795  
796 BOOL CreateChildProcess(VOID); 
797 VOID WriteToPipe(VOID); 
798 VOID ReadFromPipe(VOID); 
799 VOID ErrorExit(LPTSTR); 
800 VOID ErrMsg(LPTSTR, BOOL); 
801  
802
803 const char *
804 getArgv0(const char *cmdline)
805 {
806     const char *cp = cmdline;
807
808     while (*cp && !isspace(*cp)) cp++;
809
810     int len = cp - cmdline;
811     char *rval = (char *)malloc(len+1);
812
813     cp = cmdline;
814     char *rp = rval;
815     while (len--)
816         *rp++ = *cp++;
817
818     *rp = 0;
819     return rval;
820 }
821
822 HANDLE
823 CreateChildProcess(const char *cmdline, HANDLE in, HANDLE out, HANDLE err) 
824
825     PROCESS_INFORMATION piProcInfo; 
826     STARTUPINFO siStartInfo;
827     BOOL bFuncRetn = FALSE; 
828     
829     // Set up members of the PROCESS_INFORMATION structure. 
830     
831     ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
832     
833     // Set up members of the STARTUPINFO structure. 
834     
835     ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
836     siStartInfo.cb = sizeof(STARTUPINFO);
837     // setup new process to use supplied handles for stdin,stdout,stderr
838     // if supplied handles are not used the send a copy of our STD_HANDLE
839     // as appropriate
840     siStartInfo.dwFlags = STARTF_USESTDHANDLES;
841
842     if (in != INVALID_HANDLE_VALUE)
843         siStartInfo.hStdInput = in;
844     else
845         siStartInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
846     
847     if (out != INVALID_HANDLE_VALUE)
848         siStartInfo.hStdOutput = out;
849     else
850         siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
851     if (err != INVALID_HANDLE_VALUE)
852         siStartInfo.hStdError = err;
853     else
854         siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
855     // Create the child process. 
856     
857     char cmdLine[1024];
858     char exeFile[1024];
859     // retrive the first compont of the command line which should be the
860     // executable 
861     const char *exeName = getArgv0(cmdline);
862     // check to see if absolute path was passed to us already?
863     if (exeName[1] != ':'
864         || (strchr(cmdline, '/') == NULL
865             && strchr(cmdline, '\\') == NULL))
866     {
867         // only command name so perform search of PATH to find 
868         char *file;
869         DWORD rval = SearchPath(NULL,
870                                 exeName,
871                                 ".exe",
872                                 sizeof(exeFile),
873                                 exeFile,
874                                 &file);
875         if (rval == 0)
876             return INVALID_HANDLE_VALUE;
877         if (rval > sizeof(exeFile))
878             return INVALID_HANDLE_VALUE;
879
880     }
881     else 
882         strcpy(exeFile, exeName);
883
884     // exeFile now has absolute path to program to execute.
885     free((void *)exeName);
886     // copy original command line to pass to create process
887     strcpy(cmdLine, cmdline);
888     // try to execute program
889     bFuncRetn = CreateProcess(exeFile, 
890                               cmdLine, // command line 
891                               NULL, // process security attributes 
892                               NULL, // primary thread security attributes 
893                               TRUE, // handles are inherited 
894                               0, // creation flags 
895                               NULL, // use parent's environment 
896                               NULL, // use parent's current directory 
897                               &siStartInfo, // STARTUPINFO pointer 
898                               &piProcInfo); // receives PROCESS_INFORMATION
899     
900     if (bFuncRetn == 0) {
901         ErrorExit("CreateProcess failed\n");
902         return INVALID_HANDLE_VALUE;
903     }
904     // we don't need a handle on the process primary thread so we close
905     // this now.
906     CloseHandle(piProcInfo.hThread);
907     
908     return piProcInfo.hProcess;
909 }
910
911  
912 void
913 ErrorExit (LPTSTR lpszMessage) 
914
915     d_msg(__FILE__, __LINE__, 0, "%s", lpszMessage);
916
917  
918
919 /*
920 typedef struct s_bpipe {
921    pid_t worker_pid;
922    time_t worker_stime;
923    int wait;
924    btimer_t *timer_id;
925    FILE *rfd;
926    FILE *wfd;
927 } BPIPE;
928 */
929
930 static void
931 CloseIfValid(HANDLE handle)
932 {
933     if (handle != INVALID_HANDLE_VALUE)
934         CloseHandle(handle);
935 }
936 // include <io.h> causes to many conflicts with some of
937 // the fuctions we define here.
938 extern "C" {
939 int __cdecl _open_osfhandle(long, int);
940 }
941
942 BPIPE *
943 open_bpipe(char *prog, int wait, const char *mode)
944 {
945     HANDLE hChildStdinRd, hChildStdinWr, hChildStdinWrDup, 
946         hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup, 
947         hInputFile;
948     
949     SECURITY_ATTRIBUTES saAttr; 
950
951     BOOL fSuccess; 
952
953     hChildStdinRd = hChildStdinWr = hChildStdinWrDup = 
954         hChildStdoutRd = hChildStdoutWr = hChildStdoutRdDup = 
955         hInputFile = INVALID_HANDLE_VALUE;
956     
957     BPIPE *bpipe = (BPIPE *)malloc(sizeof(BPIPE));
958     memset((void *)bpipe, 0, sizeof(BPIPE));
959
960     int mode_read = (mode[0] == 'r');
961     int mode_write = (mode[0] == 'w' || mode[1] == 'w');
962     
963     
964     // Set the bInheritHandle flag so pipe handles are inherited. 
965     
966     saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
967     saAttr.bInheritHandle = TRUE; 
968     saAttr.lpSecurityDescriptor = NULL; 
969     
970     if (mode_read) {
971         
972         // Create a pipe for the child process's STDOUT. 
973         if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) {
974             ErrorExit("Stdout pipe creation failed\n");
975             goto cleanup;
976         }
977         // Create noninheritable read handle and close the inheritable read 
978         // handle. 
979         
980         fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
981                                    GetCurrentProcess(), &hChildStdoutRdDup , 0,
982                                    FALSE,
983                                    DUPLICATE_SAME_ACCESS);
984         if( !fSuccess ) {
985             ErrorExit("DuplicateHandle failed");
986             goto cleanup;
987         }
988         
989         CloseHandle(hChildStdoutRd);
990     }
991     
992     if (mode_write) {
993         
994         // Create a pipe for the child process's STDIN. 
995         
996         if (! CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) {
997             ErrorExit("Stdin pipe creation failed\n");
998             goto cleanup;
999         }
1000         
1001         // Duplicate the write handle to the pipe so it is not inherited. 
1002         fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr, 
1003                                    GetCurrentProcess(), &hChildStdinWrDup,
1004                                    0, 
1005                                    FALSE,                  // not inherited 
1006                                    DUPLICATE_SAME_ACCESS); 
1007         if (!fSuccess) {
1008             ErrorExit("DuplicateHandle failed");
1009             goto cleanup;
1010         }
1011         
1012         CloseHandle(hChildStdinWr); 
1013     }
1014     // spawn program with redirected handles as appropriate
1015     bpipe->worker_pid = (pid_t)
1016         CreateChildProcess(prog, // commandline
1017                            hChildStdinRd, // stdin HANDLE
1018                            hChildStdoutWr, // stdout HANDLE
1019                            hChildStdoutWr);// stderr HANDLE
1020     
1021     if ((HANDLE) bpipe->worker_pid == INVALID_HANDLE_VALUE)
1022         goto cleanup;
1023     
1024     bpipe->wait = wait;
1025     bpipe->worker_stime = time(NULL);
1026     
1027     if (mode_read) {
1028         CloseHandle(hChildStdoutWr); // close our write side so when
1029                                      // process terminates we can
1030                                      // detect eof.
1031         // ugly but convert WIN32 HANDLE to FILE*
1032         int rfd = _open_osfhandle((long)hChildStdoutRdDup, O_RDONLY);
1033         bpipe->rfd = _fdopen(rfd, "r");
1034     }
1035     if (mode_write) {
1036         CloseHandle(hChildStdinRd); // close our read side so as not
1037                                     // to interfre with child's copy
1038         // ugly but convert WIN32 HANDLE to FILE*
1039         int wfd = _open_osfhandle((long)hChildStdinWrDup, O_WRONLY);
1040         bpipe->wfd = _fdopen(wfd, "w");
1041     }
1042     
1043     if (wait > 0) {
1044         bpipe->timer_id = start_child_timer(bpipe->worker_pid, wait);
1045     }
1046     
1047     return bpipe;
1048     
1049 cleanup:
1050     
1051     CloseIfValid(hChildStdoutRd);
1052     CloseIfValid(hChildStdoutRdDup);
1053     CloseIfValid(hChildStdinWr);
1054     CloseIfValid(hChildStdinWrDup);
1055     
1056     free((void *) bpipe);
1057     
1058     return NULL;
1059 }
1060
1061 int
1062 kill(int pid, int signal)
1063 {
1064     int rval = 0;
1065     if (!TerminateProcess((HANDLE)pid, (UINT) signal))
1066         rval = -1;
1067     CloseHandle((HANDLE)pid);
1068     return rval;
1069 }
1070
1071 int
1072 close_bpipe(BPIPE *bpipe)
1073 {
1074     int rval = 0;
1075     if (bpipe->rfd) fclose(bpipe->rfd);
1076     if (bpipe->wfd) fclose(bpipe->wfd);
1077
1078     if (bpipe->wait) {
1079         int remaining_wait = bpipe->wait;
1080         do 
1081         {
1082             DWORD exitCode;
1083             if (!GetExitCodeProcess((HANDLE)bpipe->worker_pid, &exitCode))
1084             {
1085                 const char *err = errorString();
1086                 rval = GetLastError();
1087                 d_msg(__FILE__, __LINE__, 0, 
1088                       "GetExitCode error %s\n", err);
1089                 LocalFree((void *)err);
1090                 break;
1091             }
1092             
1093             if (exitCode == STILL_ACTIVE) {
1094                 bmicrosleep(1, 0);             /* wait one second */
1095                 remaining_wait--;
1096             }
1097             else break;
1098         } while(remaining_wait);
1099     }
1100     
1101     if (bpipe->timer_id) {
1102         stop_child_timer(bpipe->timer_id);
1103     }
1104     free((void *)bpipe);    
1105     return rval;
1106 }
1107
1108 int
1109 close_wpipe(BPIPE *bpipe)
1110 {
1111     int stat = 1;
1112     
1113     if (bpipe->wfd) {
1114         fflush(bpipe->wfd);
1115         if (fclose(bpipe->wfd) != 0) {
1116             stat = 0;
1117       }
1118         bpipe->wfd = NULL;
1119     }
1120     return stat;
1121 }