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