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