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