some half-baked support for windows command-arg substitutions
[ardour.git] / libs / pbd / system_exec.cc
1 /*
2     Copyright (C) 2010 Paul Davis
3     Copyright (C) 2010-2014 Robin Gareus <robin@gareus.org>
4     Copyright (C) 2005-2008 Lennart Poettering
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20 */
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <unistd.h>
26 #include <algorithm>
27
28 #include <assert.h>
29
30 #ifndef COMPILER_MSVC
31 #include <dirent.h>
32 #endif
33
34 #ifdef PLATFORM_WINDOWS
35 #include <windows.h>
36 #else
37 #include <fcntl.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 #include <sys/socket.h>
41 #include <sys/ioctl.h>
42 #include <sys/time.h>
43 #include <sys/resource.h>
44 #endif
45
46 #include <glibmm/miscutils.h>
47
48 #define USE_VFORK
49
50 #include "pbd/file_utils.h"
51 #include "pbd/search_path.h"
52 #include "pbd/system_exec.h"
53
54 using namespace std;
55 using namespace PBD;
56
57 static void * interposer_thread (void *arg);
58
59 #ifndef PLATFORM_WINDOWS /* POSIX Process only */
60 static void close_fd (int& fd) { if (fd >= 0) ::close (fd); fd = -1; }
61 #endif
62
63 #if (!defined PLATFORM_WINDOWS && defined NO_VFORK)
64 /*
65  * This function was part of libasyncns.
66  * LGPL v2.1
67  * Copyright 2005-2008 Lennart Poettering
68  */
69 static int close_allv(const int except_fds[]) {
70         struct rlimit rl;
71         int fd;
72
73 #ifdef __linux__
74
75         DIR *d;
76
77         assert(except_fds);
78
79         if ((d = opendir("/proc/self/fd"))) {
80                 struct dirent *de;
81
82                 while ((de = readdir(d))) {
83                         int found;
84                         long l;
85                         char *e = NULL;
86                         int i;
87
88                         if (de->d_name[0] == '.')
89                                         continue;
90
91                         errno = 0;
92                         l = strtol(de->d_name, &e, 10);
93                         if (errno != 0 || !e || *e) {
94                                 closedir(d);
95                                 errno = EINVAL;
96                                 return -1;
97                         }
98
99                         fd = (int) l;
100
101                         if ((long) fd != l) {
102                                 closedir(d);
103                                 errno = EINVAL;
104                                 return -1;
105                         }
106
107                         if (fd < 3)
108                                 continue;
109
110                         if (fd == dirfd(d))
111                                 continue;
112
113                         found = 0;
114                         for (i = 0; except_fds[i] >= 0; i++)
115                                 if (except_fds[i] == fd) {
116                                                 found = 1;
117                                                 break;
118                                 }
119
120                         if (found) continue;
121
122                         if (close(fd) < 0) {
123                                 int saved_errno;
124
125                                 saved_errno = errno;
126                                 closedir(d);
127                                 errno = saved_errno;
128
129                                 return -1;
130                         }
131                 }
132
133                 closedir(d);
134                 return 0;
135         }
136
137 #endif
138
139         if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
140                 return -1;
141
142         for (fd = 0; fd < (int) rl.rlim_max; fd++) {
143                 int i;
144
145                 if (fd <= 3)
146                                 continue;
147
148                 for (i = 0; except_fds[i] >= 0; i++)
149                         if (except_fds[i] == fd)
150                                 continue;
151
152                 if (close(fd) < 0 && errno != EBADF)
153                         return -1;
154         }
155
156         return 0;
157 }
158 #endif /* not on windows, nor vfork */
159
160 void
161 SystemExec::init ()
162 {
163         pthread_mutex_init(&write_lock, NULL);
164         thread_active=false;
165         pid = 0;
166         pin[1] = -1;
167         nicelevel = 0;
168         envp = NULL;
169 #ifdef PLATFORM_WINDOWS
170         stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
171         stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
172         stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
173         w_args = NULL;
174 #endif
175 }
176
177 SystemExec::SystemExec (std::string c, std::string a)
178         : cmd(c)
179 {
180         init ();
181
182         argp = NULL;
183         make_envp();
184         make_argp(a);
185 }
186
187 SystemExec::SystemExec (std::string c, char **a)
188         : cmd(c) , argp(a)
189 {
190         init ();
191
192 #ifdef PLATFORM_WINDOWS
193         make_wargs(a);
194 #endif
195         make_envp();
196 }
197
198 SystemExec::SystemExec (std::string command, const std::map<char, std::string> subs)
199 {
200         init ();
201         make_argp_escaped(command, subs);
202
203 #ifdef PLATFORM_WINDOWS
204         std::string wa;
205         for (int i = 0; argp[i]; ++i) {
206                 if (!wa.empty ()) wa += " ";
207                 wa += '"' + argp[i] + '"';
208         }
209         w_args = strdup(wa.c_str());
210 #else
211         if (find_file (Searchpath (Glib::getenv ("PATH")), argp[0], cmd)) {
212                 // argp[0] exists in $PATH` - set it to the actual path where it was found
213                 free (argp[0]);
214                 argp[0] = strdup(cmd.c_str ());
215         }
216         // else argp[0] not found in path - leave it as-is, it might be an absolute path
217
218         // Glib::find_program_in_path () is only available in Glib >= 2.28
219         // cmd = Glib::find_program_in_path (argp[0]);
220 #endif
221         make_envp();
222 }
223
224 void
225 SystemExec::make_argp_escaped(std::string command, const std::map<char, std::string> subs)
226 {
227
228         int inquotes = 0;
229         int n = 0;
230         size_t i = 0;
231         std::string arg = "";
232
233         argp = (char **) malloc(sizeof(char *));
234
235         for (i = 0; i <= command.length(); i++) { // include terminating '\0'
236                 char c = command.c_str()[i];
237                 if (inquotes) {
238                         if (c == '"') {
239                                 inquotes = 0;
240                         } else {
241                                 // still in quotes - just copy
242                                 arg += c;
243                         }
244                 } else switch (c) {
245                         case '%' :
246                                 c = command.c_str()[++i];
247                                 if (c == '%' || c == '\0') {
248                                         // "%%", "%" at end-of-string => "%"
249                                         arg += '%';
250                                 } else {
251                                         // search subs for string to substitute for char
252                                         std::map<char, std::string>::const_iterator s = subs.find(c);
253                                         if (s != subs.end()) {
254                                                 // found substitution
255                                                 arg += s->second;
256                                         } else {
257                                                 // not a valid substitution, just copy
258                                                 arg += '%';
259                                                 arg += c;
260                                         }
261                                 }
262                                 break;
263                         case '\\':
264                                 c = command.c_str()[++i];
265                                 switch (c) {
266                                         case ' ' :
267                                         case '"' : arg += c; break; // "\\", "\" at end-of-string => "\"
268                                         case '\0':
269                                         case '\\': arg += '\\'; break;
270                                         default  : arg += '\\'; arg += c; break;
271                                 }
272                                 break;
273                         case '"' :
274                                 inquotes = 1;
275                                 break;
276                         case ' ' :
277                         case '\t':
278                         case '\0':
279                                 if (arg.length() > 0) {
280                                         // if there wasn't already a space or tab, start a new parameter
281                                         argp = (char **) realloc(argp, (n + 2) * sizeof(char *));
282                                         argp[n++] = strdup (arg.c_str());
283                                         arg = "";
284                                 }
285                                 break;
286                         default :
287                                 arg += c;
288                                 break;
289                 }
290         }
291         argp[n] = NULL;
292 }
293
294 SystemExec::~SystemExec ()
295 {
296         terminate ();
297         if (envp) {
298                 for (int i=0;envp[i];++i) {
299                         free(envp[i]);
300                 }
301                 free (envp);
302         }
303         if (argp) {
304                 for (int i=0;argp[i];++i) {
305                         free(argp[i]);
306                 }
307                 free (argp);
308         }
309 #ifdef PLATFORM_WINDOWS
310         if (w_args) free(w_args);
311 #endif
312         pthread_mutex_destroy(&write_lock);
313 }
314
315 static void *
316 interposer_thread (void *arg) {
317         SystemExec *sex = static_cast<SystemExec *>(arg);
318         sex->output_interposer();
319         pthread_exit(0);
320         return 0;
321 }
322
323 string
324 SystemExec::to_s () const
325 {
326         stringstream out;
327         if (argp) {
328                 for (int i = 0; argp[i]; ++i) {
329                         out << argp[i] << " ";
330                 }
331         }
332         return out.str();
333 }
334
335 #ifdef PLATFORM_WINDOWS /* Windows Process */
336
337 /* HELPER FUNCTIONS */
338
339 static void create_pipe (HANDLE *pipe, bool in) {
340         SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
341         HANDLE tmpHandle;
342         if (in) {
343                 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
344                 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
345         } else {
346                 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
347                 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
348         }
349         CloseHandle(tmpHandle);
350 }
351
352 static void destroy_pipe (HANDLE pipe[2]) {
353         if (pipe[0] != INVALID_HANDLE_VALUE) {
354                 CloseHandle(pipe[0]);
355                 pipe[0] = INVALID_HANDLE_VALUE;
356         }
357         if (pipe[1] != INVALID_HANDLE_VALUE) {
358                 CloseHandle(pipe[1]);
359                 pipe[1] = INVALID_HANDLE_VALUE;
360         }
361 }
362
363 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
364 {
365         DWORD currentProcId = 0;
366         GetWindowThreadProcessId(hwnd, &currentProcId);
367         if (currentProcId == (DWORD)procId)
368                 PostMessage(hwnd, WM_CLOSE, 0, 0);
369         return TRUE;
370 }
371
372 /* PROCESS API */
373
374 void
375 SystemExec::make_envp() {
376         ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
377 }
378
379 void
380 SystemExec::make_wargs(char **a) {
381         std::string wa = cmd;
382         if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
383         std::replace(cmd.begin(), cmd.end(), '/', '\\' );
384         char **tmp = ++a;
385         while (tmp && *tmp) {
386                 wa.append(" \"");
387                 wa.append(*tmp);
388                 if (strlen(*tmp) > 0 && (*tmp)[strlen(*tmp) - 1] == '\\') {
389                         wa.append("\\");
390                 }
391                 wa.append("\"");
392                 tmp++;
393         }
394         w_args = strdup(wa.c_str());
395 }
396
397 void
398 SystemExec::make_argp(std::string args) {
399         std::string wa = cmd;
400         if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
401         std::replace(cmd.begin(), cmd.end(), '/', '\\' );
402         wa.append(" ");
403         wa.append(args);
404         w_args = strdup(wa.c_str());
405 }
406
407 void
408 SystemExec::terminate ()
409 {
410         ::pthread_mutex_lock(&write_lock);
411
412         close_stdin();
413
414         if (pid) {
415                 /* terminate */
416                 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
417                 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
418
419                 /* kill ! */
420                 TerminateProcess(pid->hProcess, 0xf291);
421
422                 CloseHandle(pid->hThread);
423                 CloseHandle(pid->hProcess);
424                 destroy_pipe(stdinP);
425                 destroy_pipe(stdoutP);
426                 destroy_pipe(stderrP);
427                 delete pid;
428                 pid=0;
429         }
430         ::pthread_mutex_unlock(&write_lock);
431 }
432
433 int
434 SystemExec::wait (int options)
435 {
436         while (is_running()) {
437                 WaitForSingleObject(pid->hProcess, 40);
438         }
439         return 0;
440 }
441
442 bool
443 SystemExec::is_running ()
444 {
445         if (!pid) return false;
446         DWORD exit_code;
447         if (GetExitCodeProcess(pid->hProcess, &exit_code)) {
448                 if (exit_code == STILL_ACTIVE) return true;
449         }
450         return false;
451 }
452
453 int
454 SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
455 {
456         char* working_dir = 0;
457
458         if (pid) { return 0; }
459
460         pid = new PROCESS_INFORMATION;
461         memset(pid, 0, sizeof(PROCESS_INFORMATION));
462
463         create_pipe(stdinP, true);
464         create_pipe(stdoutP, false);
465
466         if (stderr_mode == 2) {
467         /* merge stout & stderr */
468                 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
469         } else if (stderr_mode == 1) {
470                 //TODO read/flush this pipe or close it...
471                 create_pipe(stderrP, false);
472         } else {
473                 //TODO: keep stderr of this process mode.
474         }
475
476         bool success = false;
477         STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
478                 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
479                 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
480                 0, 0, 0,
481                 STARTF_USESTDHANDLES,
482                 0, 0, 0,
483                 stdinP[0], stdoutP[1], stderrP[1]
484         };
485
486         success = CreateProcess(0, w_args,
487                 0, 0, /* bInheritHandles = */ TRUE,
488                 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
489                 /*env = */ 0,
490                 working_dir,
491                 &startupInfo, pid);
492
493         if (stdinP[0] != INVALID_HANDLE_VALUE) {
494                 CloseHandle(stdinP[0]);
495                 stdinP[0] = INVALID_HANDLE_VALUE;
496         }
497         if (stdoutP[1] != INVALID_HANDLE_VALUE) {
498                 CloseHandle(stdoutP[1]);
499                 stdoutP[1] = INVALID_HANDLE_VALUE;
500         }
501         if (stderrP[1] != INVALID_HANDLE_VALUE) {
502                 CloseHandle(stderrP[1]);
503                 stderrP[1] = INVALID_HANDLE_VALUE;
504         }
505
506         if (!success) {
507                 CloseHandle(pid->hThread);
508                 CloseHandle(pid->hProcess);
509                 destroy_pipe(stdinP);
510                 destroy_pipe(stdoutP);
511                 destroy_pipe(stderrP);
512                 delete pid;
513                 pid=0;
514                 return -1;
515         }
516
517         int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
518         thread_active=true;
519         if (rv) {
520                 thread_active=false;
521                 terminate();
522                 return -2;
523         }
524         Sleep(20);
525         return 0;
526 }
527
528 void
529 SystemExec::output_interposer()
530 {
531         DWORD bytesRead = 0;
532         char data[BUFSIZ];
533 #if 0 // untested code to set up nonblocking
534         unsigned long l = 1;
535         ioctlsocket(stdoutP[0], FIONBIO, &l);
536 #endif
537         while(1) {
538 #if 0 // for non-blocking pipes..
539                 DWORD bytesAvail = 0;
540                 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
541                 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
542 #endif
543                 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
544                 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) {
545                         DWORD err =  GetLastError();
546                         if (err == ERROR_IO_PENDING) continue;
547                         break;
548                 }
549                 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
550                 data[bytesRead] = 0;
551                 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
552         }
553         Terminated();/* EMIT SIGNAL */
554         pthread_exit(0);
555 }
556
557 void
558 SystemExec::close_stdin()
559 {
560         if (stdinP[0]!= INVALID_HANDLE_VALUE)  FlushFileBuffers(stdinP[0]);
561         if (stdinP[1]!= INVALID_HANDLE_VALUE)  FlushFileBuffers(stdinP[1]);
562         Sleep(200);
563         destroy_pipe(stdinP);
564 }
565
566 int
567 SystemExec::write_to_stdin(std::string d, size_t len)
568 {
569         const char *data;
570         DWORD r,c;
571
572         ::pthread_mutex_lock(&write_lock);
573
574         data=d.c_str();
575         if (len == 0) {
576                 len=(d.length());
577         }
578         c=0;
579         while (c < len) {
580                 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
581                         if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
582                                 Sleep(100);
583                                 continue;
584                         } else {
585                                 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
586                                 break;
587                         }
588                 }
589                 c += r;
590         }
591         ::pthread_mutex_unlock(&write_lock);
592         return c;
593 }
594
595
596 /* end windows process */
597 #else
598 /* UNIX/POSIX process */
599
600 extern char **environ;
601 void
602 SystemExec::make_envp() {
603         int i=0;
604         envp = (char **) calloc(1, sizeof(char*));
605         /* copy current environment */
606         for (i=0;environ[i];++i) {
607           envp[i] = strdup(environ[i]);
608           envp = (char **) realloc(envp, (i+2) * sizeof(char*));
609         }
610         envp[i] = 0;
611 }
612
613 void
614 SystemExec::make_argp(std::string args) {
615         int argn = 1;
616         char *cp1;
617         char *cp2;
618
619         char *carg = strdup(args.c_str());
620
621         argp = (char **) malloc((argn + 1) * sizeof(char *));
622         if (argp == (char **) 0) {
623                 free(carg);
624                 return; // FATAL
625         }
626
627         argp[0] = strdup(cmd.c_str());
628
629         /* TODO: quotations and escapes
630          * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
631          *
632          * It's actually not needed. All relevant invocations specify 'argp' directly.
633          * Only 'xjadeo -L -R' uses this function and that uses neither quotations
634          * nor arguments with white-space.
635          */
636         for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
637                 if (*cp2 == ' ') {
638                         *cp2 = '\0';
639                         argp[argn++] = strdup(cp1);
640                         cp1 = cp2 + 1;
641                         argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
642                 }
643         }
644         if (cp2 != cp1) {
645                 argp[argn++] = strdup(cp1);
646                 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
647         }
648         argp[argn] = (char *) 0;
649         free(carg);
650 }
651
652
653
654 void
655 SystemExec::terminate ()
656 {
657         ::pthread_mutex_lock(&write_lock);
658
659         /* close stdin in an attempt to get the child to exit cleanly.
660          */
661
662         close_stdin();
663
664         if (pid) {
665                 ::usleep(200000);
666                 sched_yield();
667                 wait(WNOHANG);
668         }
669
670         /* if pid is non-zero, the child task is still executing (i.e. it did
671          * not exit in response to stdin being closed). try to kill it.
672          */
673
674         if (pid) {
675                 ::kill(pid, SIGTERM);
676                 ::usleep(250000);
677                 sched_yield();
678                 wait(WNOHANG);
679         }
680
681         /* if pid is non-zero, the child task is STILL executing after being
682          * sent SIGTERM. Act tough ... send SIGKILL
683          */
684
685         if (pid) {
686                 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
687                 ::kill(pid, SIGKILL);
688         }
689
690         wait();
691         if (thread_active) pthread_join(thread_id_tt, NULL);
692         thread_active = false;
693         assert(pid == 0);
694         ::pthread_mutex_unlock(&write_lock);
695 }
696
697 int
698 SystemExec::wait (int options)
699 {
700         int status=0;
701         int ret;
702
703         if (pid==0) return -1;
704
705         ret = waitpid (pid, &status, options);
706
707         if (ret == pid) {
708                 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
709                         pid=0;
710                 }
711         } else {
712                 if (ret != 0) {
713                         if (errno == ECHILD) {
714                                 /* no currently running children, reset pid */
715                                 pid=0;
716                         }
717                 } /* else the process is still running */
718         }
719         return status;
720 }
721
722 bool
723 SystemExec::is_running ()
724 {
725         int status=0;
726         if (pid==0) return false;
727         if (::waitpid(pid, &status, WNOHANG)==0) return true;
728         return false;
729 }
730
731 int
732 SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
733 {
734         if (is_running()) {
735                 return 0; // mmh what to return here?
736         }
737         int r;
738
739         if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
740                 /* Something unexpected went wrong creating a pipe. */
741                 return -1;
742         }
743
744 #ifndef NO_VFORK
745         r = ::vfork();
746 #else
747         r = ::fork();
748 #endif
749         if (r < 0) {
750                 /* failed to fork */
751                 return -2;
752         }
753
754         if (r > 0) {
755                 /* main */
756                 pid=r;
757
758                 /* check if execve was successful. */
759                 close_fd(pok[1]);
760                 char buf;
761                 for ( ;; ) {
762                         ssize_t n = ::read(pok[0], &buf, 1 );
763                         if ( n==1 ) {
764                                 /* child process returned from execve */
765                                 pid=0;
766                                 close_fd(pok[0]);
767                                 close_fd(pok[1]);
768                                 close_fd(pin[1]);
769                                 close_fd(pin[0]);
770                                 close_fd(pout[1]);
771                                 close_fd(pout[0]);
772                                 return -3;
773                         } else if ( n==-1 ) {
774                                  if ( errno==EAGAIN || errno==EINTR )
775                                          continue;
776                         }
777                         break;
778                 }
779                 close_fd(pok[0]);
780                 /* child started successfully */
781
782                 close_fd(pout[1]);
783                 close_fd(pin[0]);
784                 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
785
786                 thread_active=true;
787                 if (rv) {
788                         thread_active=false;
789                         terminate();
790                         return -2;
791                 }
792                 return 0; /* all systems go - return to main */
793         }
794
795 #ifdef NO_VFORK
796         /* child process - exec external process */
797         close_fd(pok[0]);
798         ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
799
800         close_fd(pin[1]);
801         if (pin[0] != STDIN_FILENO) {
802           ::dup2(pin[0], STDIN_FILENO);
803         }
804         close_fd(pin[0]);
805         close_fd(pout[0]);
806         if (pout[1] != STDOUT_FILENO) {
807                 ::dup2(pout[1], STDOUT_FILENO);
808         }
809
810         if (stderr_mode == 2) {
811                 /* merge STDERR into output */
812                 if (pout[1] != STDERR_FILENO) {
813                         ::dup2(pout[1], STDERR_FILENO);
814                 }
815         } else if (stderr_mode == 1) {
816                 /* ignore STDERR */
817                 ::close(STDERR_FILENO);
818         } else {
819                 /* keep STDERR */
820         }
821
822         if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
823                 close_fd(pout[1]);
824         }
825
826         if (nicelevel !=0) {
827                 ::nice(nicelevel);
828         }
829
830 #ifdef HAVE_SIGSET
831         sigset(SIGPIPE, SIG_DFL);
832 #else
833         signal(SIGPIPE, SIG_DFL);
834 #endif
835         if (!vfork_exec_wrapper) {
836                 error << _("Cannot start external process, no vfork wrapper") << endmsg;
837                 return -1;
838         }
839
840         int good_fds[2] = { pok[1],  -1 };
841         close_allv(good_fds);
842
843         ::execve(argp[0], argp, envp);
844         /* if we reach here something went wrong.. */
845         char buf = 0;
846         (void) ::write(pok[1], &buf, 1 );
847         close_fd(pok[1]);
848         exit(-1);
849         return -1;
850 #else
851
852         /* XXX this should be done before vfork()
853          * calling malloc here only increases the time vfork() blocks
854          */
855         int argn = 0;
856         for (int i=0;argp[i];++i) { argn++; }
857         char **argx = (char **) malloc((argn + 10) * sizeof(char *));
858         argx[0] = strdup(vfork_exec_wrapper); // XXX
859
860 #define FDARG(NUM, FDN) \
861         argx[NUM] = (char*) calloc(6, sizeof(char)); snprintf(argx[NUM], 6, "%d", FDN);
862
863         FDARG(1, pok[0])
864         FDARG(2, pok[1])
865         FDARG(3, pin[0])
866         FDARG(4, pin[1])
867         FDARG(5, pout[0])
868         FDARG(6, pout[1])
869         FDARG(7, stderr_mode)
870         FDARG(8, nicelevel)
871
872         for (int i=0;argp[i];++i) {
873                 argx[9+i] = argp[i];
874         }
875         argx[argn+9] = NULL;
876
877         ::execve(argx[0], argx, envp);
878
879         /* if we reach here something went wrong.. */
880         char buf = 0;
881         (void) ::write(pok[1], &buf, 1 );
882         close_fd(pok[1]);
883         exit(-1);
884         return -1;
885 #endif
886 }
887
888 void
889 SystemExec::output_interposer()
890 {
891         int rfd=pout[0];
892         char buf[BUFSIZ];
893         ssize_t r;
894         unsigned long l = 1;
895
896         ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
897
898         for (;fcntl(rfd, F_GETFL)!=-1;) {
899                 r = read(rfd, buf, sizeof(buf));
900                 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
901                         fd_set rfds;
902                         struct timeval tv;
903                         FD_ZERO(&rfds);
904                         FD_SET(rfd, &rfds);
905                         tv.tv_sec = 0;
906                         tv.tv_usec = 10000;
907                         int rv = select(1, &rfds, NULL, NULL, &tv);
908                         if (rv == -1) {
909                                 break;
910                         }
911                         continue;
912                 }
913                 if (r <= 0) {
914                         break;
915                 }
916                 buf[r]=0;
917                 std::string rv = std::string(buf,r); // TODO: check allocation strategy
918                 ReadStdout(rv, r);/* EMIT SIGNAL */
919         }
920         Terminated();/* EMIT SIGNAL */
921         pthread_exit(0);
922 }
923
924 void
925 SystemExec::close_stdin()
926 {
927         if (pin[1]<0) return;
928         close_fd(pin[0]);
929         close_fd(pin[1]);
930         close_fd(pout[0]);
931         close_fd(pout[1]);
932 }
933
934 int
935 SystemExec::write_to_stdin(std::string d, size_t len)
936 {
937         const char *data;
938         ssize_t r;
939         size_t c;
940         ::pthread_mutex_lock(&write_lock);
941
942         data=d.c_str();
943         if (len == 0) {
944                 len=(d.length());
945         }
946         c=0;
947         while (c < len) {
948                 for (;;) {
949                         r=::write(pin[1], data+c, len-c);
950                         if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
951                                 sleep(1);
952                                 continue;
953                         }
954                         if ((size_t) r != (len-c)) {
955                                 ::pthread_mutex_unlock(&write_lock);
956                                 return c;
957                         }
958                         break;
959                 }
960                 c += r;
961         }
962         fsync(pin[1]);
963         ::pthread_mutex_unlock(&write_lock);
964         return c;
965 }
966
967 #endif // end UNIX process