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