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