2 Copyright (C) 2010 Paul Davis
3 Copyright (C) 2010-2014 Robin Gareus <robin@gareus.org>
4 Copyright (C) 2005-2008 Lennart Poettering
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.
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.
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.
34 #ifdef PLATFORM_WINDOWS
38 #include <sys/types.h>
40 #include <sys/socket.h>
41 #include <sys/ioctl.h>
43 #include <sys/resource.h>
49 #include "pbd/system_exec.h"
54 static void * interposer_thread (void *arg);
55 static void close_fd (int& fd) { if (fd >= 0) ::close (fd); fd = -1; }
57 #if (!defined PLATFORM_WINDOWS && defined NO_VFORK)
59 * This function was part of libasyncns.
61 * Copyright 2005-2008 Lennart Poettering
63 static int close_allv(const int except_fds[]) {
73 if ((d = opendir("/proc/self/fd"))) {
76 while ((de = readdir(d))) {
82 if (de->d_name[0] == '.')
86 l = strtol(de->d_name, &e, 10);
87 if (errno != 0 || !e || *e) {
108 for (i = 0; except_fds[i] >= 0; i++)
109 if (except_fds[i] == fd) {
133 if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
136 for (fd = 0; fd < (int) rl.rlim_max; fd++) {
142 for (i = 0; except_fds[i] >= 0; i++)
143 if (except_fds[i] == fd)
146 if (close(fd) < 0 && errno != EBADF)
152 #endif /* not on windows, nor vfork */
155 SystemExec::SystemExec (std::string c, std::string a)
158 pthread_mutex_init(&write_lock, NULL);
165 #ifdef PLATFORM_WINDOWS
166 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
167 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
168 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
174 SystemExec::SystemExec (std::string c, char **a)
177 pthread_mutex_init(&write_lock, NULL);
183 #ifdef PLATFORM_WINDOWS
184 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
185 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
186 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
192 SystemExec::~SystemExec ()
196 for (int i=0;envp[i];++i) {
202 for (int i=0;argp[i];++i) {
207 #ifdef PLATFORM_WINDOWS
208 if (w_args) free(w_args);
210 pthread_mutex_destroy(&write_lock);
214 interposer_thread (void *arg) {
215 SystemExec *sex = static_cast<SystemExec *>(arg);
216 sex->output_interposer();
221 #ifdef PLATFORM_WINDOWS /* Windows Process */
223 /* HELPER FUNCTIONS */
225 static void create_pipe (HANDLE *pipe, bool in) {
226 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
229 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
230 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
232 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
233 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
235 CloseHandle(tmpHandle);
238 static void destroy_pipe (HANDLE pipe[2]) {
239 if (pipe[0] != INVALID_HANDLE_VALUE) {
240 CloseHandle(pipe[0]);
241 pipe[0] = INVALID_HANDLE_VALUE;
243 if (pipe[1] != INVALID_HANDLE_VALUE) {
244 CloseHandle(pipe[1]);
245 pipe[1] = INVALID_HANDLE_VALUE;
249 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
251 DWORD currentProcId = 0;
252 GetWindowThreadProcessId(hwnd, ¤tProcId);
253 if (currentProcId == (DWORD)procId)
254 PostMessage(hwnd, WM_CLOSE, 0, 0);
261 SystemExec::make_envp() {
262 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
266 SystemExec::make_wargs(char **a) {
267 std::string wa = cmd;
268 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
269 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
271 while (tmp && *tmp) {
273 std::string arg(*tmp);
274 size_t start_pos = 0;
275 while((start_pos = arg.find("\\", start_pos)) != std::string::npos) {
276 arg.replace(start_pos, 1, "\\\\");
283 w_args = strdup(wa.c_str());
287 SystemExec::make_argp(std::string args) {
288 std::string wa = cmd;
289 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
290 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
293 w_args = strdup(wa.c_str());
297 SystemExec::terminate ()
299 ::pthread_mutex_lock(&write_lock);
302 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
303 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
306 TerminateProcess(pid->hProcess, 0xf291);
308 CloseHandle(pid->hThread);
309 CloseHandle(pid->hProcess);
310 destroy_pipe(stdinP);
311 destroy_pipe(stdoutP);
312 destroy_pipe(stderrP);
316 ::pthread_mutex_unlock(&write_lock);
320 SystemExec::wait (int options)
322 while (is_running()) {
323 WaitForSingleObject(pid->hProcess, INFINITE);
330 SystemExec::is_running ()
332 return pid?true:false;
336 SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
338 char* working_dir = 0;
340 if (pid) { return 0; }
342 pid = new PROCESS_INFORMATION;
343 memset(pid, 0, sizeof(PROCESS_INFORMATION));
345 create_pipe(stdinP, true);
346 create_pipe(stdoutP, false);
348 if (stderr_mode == 2) {
349 /* merge stout & stderr */
350 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
351 } else if (stderr_mode == 1) {
352 //TODO read/flush this pipe or close it...
353 create_pipe(stderrP, false);
355 //TODO: keep stderr of this process mode.
358 bool success = false;
359 STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
360 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
361 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
363 STARTF_USESTDHANDLES,
365 stdinP[0], stdoutP[1], stderrP[1]
368 success = CreateProcess(0, w_args,
369 0, 0, /* bInheritHandles = */ TRUE,
370 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
375 if (stdinP[0] != INVALID_HANDLE_VALUE) {
376 CloseHandle(stdinP[0]);
377 stdinP[0] = INVALID_HANDLE_VALUE;
379 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
380 CloseHandle(stdoutP[1]);
381 stdoutP[1] = INVALID_HANDLE_VALUE;
383 if (stderrP[1] != INVALID_HANDLE_VALUE) {
384 CloseHandle(stderrP[1]);
385 stderrP[1] = INVALID_HANDLE_VALUE;
389 CloseHandle(pid->hThread);
390 CloseHandle(pid->hProcess);
391 destroy_pipe(stdinP);
392 destroy_pipe(stdoutP);
393 destroy_pipe(stderrP);
399 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
411 SystemExec::output_interposer()
415 #if 0 // untested code to set up nonblocking
417 ioctlsocket(stdoutP[0], FIONBIO, &l);
420 #if 0 // for non-blocking pipes..
421 DWORD bytesAvail = 0;
422 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
423 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
425 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
426 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) {
427 DWORD err = GetLastError();
428 if (err == ERROR_IO_PENDING) continue;
431 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
433 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
435 Terminated();/* EMIT SIGNAL */
439 SystemExec::close_stdin()
441 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
442 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
444 destroy_pipe(stdinP);
448 SystemExec::write_to_stdin(std::string d, size_t len)
453 ::pthread_mutex_lock(&write_lock);
461 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
462 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
466 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
472 ::pthread_mutex_unlock(&write_lock);
477 /* end windows process */
479 /* UNIX/POSIX process */
481 extern char **environ;
483 SystemExec::make_envp() {
485 envp = (char **) calloc(1, sizeof(char*));
486 /* copy current environment */
487 for (i=0;environ[i];++i) {
488 envp[i] = strdup(environ[i]);
489 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
495 SystemExec::make_argp(std::string args) {
500 char *carg = strdup(args.c_str());
502 argp = (char **) malloc((argn + 1) * sizeof(char *));
503 if (argp == (char **) 0) {
508 argp[0] = strdup(cmd.c_str());
510 /* TODO: quotations and escapes
511 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
513 * It's actually not needed. All relevant invocations specify 'argp' directly.
514 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
515 * nor arguments with white-space.
517 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
520 argp[argn++] = strdup(cp1);
522 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
526 argp[argn++] = strdup(cp1);
527 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
529 argp[argn] = (char *) 0;
536 SystemExec::terminate ()
538 ::pthread_mutex_lock(&write_lock);
540 /* close stdin in an attempt to get the child to exit cleanly.
551 /* if pid is non-zero, the child task is still executing (i.e. it did
552 * not exit in response to stdin being closed). try to kill it.
556 ::kill(pid, SIGTERM);
562 /* if pid is non-zero, the child task is STILL executing after being
563 * sent SIGTERM. Act tough ... send SIGKILL
567 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
568 ::kill(pid, SIGKILL);
572 if (thread_active) pthread_join(thread_id_tt, NULL);
573 thread_active = false;
574 ::pthread_mutex_unlock(&write_lock);
578 SystemExec::wait (int options)
583 if (pid==0) return -1;
585 ret = waitpid (pid, &status, options);
588 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
593 if (errno == ECHILD) {
594 /* no currently running children, reset pid */
597 } /* else the process is still running */
603 SystemExec::is_running ()
606 if (pid==0) return false;
607 if (::waitpid(pid, &status, WNOHANG)==0) return true;
612 SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
615 return 0; // mmh what to return here?
619 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
620 /* Something unexpected went wrong creating a pipe. */
638 /* check if execve was successful. */
642 ssize_t n = ::read(pok[0], &buf, 1 );
644 /* child process returned from execve */
653 } else if ( n==-1 ) {
654 if ( errno==EAGAIN || errno==EINTR )
660 /* child started successfully */
664 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
672 return 0; /* all systems go - return to main */
676 /* child process - exec external process */
678 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
681 if (pin[0] != STDIN_FILENO) {
682 ::dup2(pin[0], STDIN_FILENO);
686 if (pout[1] != STDOUT_FILENO) {
687 ::dup2(pout[1], STDOUT_FILENO);
690 if (stderr_mode == 2) {
691 /* merge STDERR into output */
692 if (pout[1] != STDERR_FILENO) {
693 ::dup2(pout[1], STDERR_FILENO);
695 } else if (stderr_mode == 1) {
697 ::close(STDERR_FILENO);
702 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
711 sigset(SIGPIPE, SIG_DFL);
713 signal(SIGPIPE, SIG_DFL);
716 int good_fds[2] = { pok[1], -1 };
717 close_allv(good_fds);
719 ::execve(argp[0], argp, envp);
720 /* if we reach here something went wrong.. */
722 (void) ::write(pok[1], &buf, 1 );
728 /* XXX this should be done before vfork()
729 * calling malloc here only increases the time vfork() blocks
732 for (int i=0;argp[i];++i) { argn++; }
733 char **argx = (char **) malloc((argn + 10) * sizeof(char *));
734 argx[0] = strdup(vfork_exec_wrapper); // XXX
736 #define FDARG(NUM, FDN) \
737 argx[NUM] = (char*) calloc(6, sizeof(char)); snprintf(argx[NUM], 6, "%d", FDN);
745 FDARG(7, stderr_mode)
748 for (int i=0;argp[i];++i) {
753 ::execve(argx[0], argx, envp);
755 /* if we reach here something went wrong.. */
757 (void) ::write(pok[1], &buf, 1 );
765 SystemExec::output_interposer()
772 ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
774 for (;fcntl(rfd, F_GETFL)!=-1;) {
775 r = read(rfd, buf, sizeof(buf));
776 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
784 std::string rv = std::string(buf,r); // TODO: check allocation strategy
785 ReadStdout(rv, r);/* EMIT SIGNAL */
787 Terminated();/* EMIT SIGNAL */
791 SystemExec::close_stdin()
793 if (pin[1]<0) return;
801 SystemExec::write_to_stdin(std::string d, size_t len)
806 ::pthread_mutex_lock(&write_lock);
815 r=::write(pin[1], data+c, len-c);
816 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
820 if ((size_t) r != (len-c)) {
821 ::pthread_mutex_unlock(&write_lock);
829 ::pthread_mutex_unlock(&write_lock);
833 #endif // end UNIX process