2 Copyright (C) 2010 Paul Davis
3 Copyright 2005-2008 Lennart Poettering
4 Author: Robin Gareus <robin@gareus.org>
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 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <sys/ioctl.h>
39 #include <sys/resource.h>
43 #include "pbd/system_exec.h"
46 void * interposer_thread (void *arg);
48 static void close_fd (int& fd) { if (fd >= 0) ::close (fd); fd = -1; }
52 * This function was part of libasyncns.
54 * Copyright 2005-2008 Lennart Poettering
56 static int close_allv(const int except_fds[]) {
66 if ((d = opendir("/proc/self/fd"))) {
69 while ((de = readdir(d))) {
75 if (de->d_name[0] == '.')
79 l = strtol(de->d_name, &e, 10);
80 if (errno != 0 || !e || *e) {
101 for (i = 0; except_fds[i] >= 0; i++)
102 if (except_fds[i] == fd) {
126 if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
129 for (fd = 0; fd < (int) rl.rlim_max; fd++) {
135 for (i = 0; except_fds[i] >= 0; i++)
136 if (except_fds[i] == fd)
139 if (close(fd) < 0 && errno != EBADF)
145 #endif /* not on windows */
150 pthread_mutex_init(&write_lock, NULL);
157 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
158 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
159 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
163 SystemExec::SystemExec (std::string c, std::string a)
173 SystemExec::SystemExec (std::string c, char **a)
184 SystemExec::SystemExec (std::string command, const std::map<char, std::string> subs)
187 make_argp_escaped(command, subs);
189 // cmd = strdup(argp[0]);
194 SystemExec::make_argp_escaped(std::string command, const std::map<char, std::string> subs)
200 std::string arg = "";
202 argp = (char **) malloc(sizeof(char *));
204 for (i = 0; i <= command.length(); i++) { // include terminating '\0'
205 char c = command.c_str()[i];
210 // still in quotes - just copy
215 c = command.c_str()[++i];
216 if (c == '%' || c == '\0') {
217 // "%%", "%" at end-of-string => "%"
220 // search subs for string to substitute for char
221 std::map<char, std::string>::const_iterator s = subs.find(c);
222 if (s != subs.end()) {
223 // found substitution
226 // not a valid substitution, just copy
233 c = command.c_str()[++i];
236 case '"' : arg += c; break; // "\\", "\" at end-of-string => "\"
238 case '\\': arg += '\\'; break;
239 default : arg += '\\'; arg += c; break;
248 if (arg.length() > 0) {
249 // if there wasn't already a space or tab, start a new parameter
250 argp = (char **) realloc(argp, (n + 2) * sizeof(char *));
251 argp[n++] = strdup (arg.c_str());
265 std::cerr << "argv[" << n << "] == \"" << p << "\"" << std::endl;
271 SystemExec::~SystemExec ()
275 for (int i=0;envp[i];++i) {
281 for (int i=0;argp[i];++i) {
287 if (w_args) free(w_args);
289 pthread_mutex_destroy(&write_lock);
293 interposer_thread (void *arg) {
294 SystemExec *sex = static_cast<SystemExec *>(arg);
295 sex->output_interposer();
300 #ifdef __WIN32__ /* Windows Process */
302 /* HELPER FUNCTIONS */
304 static void create_pipe (HANDLE *pipe, bool in) {
305 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
308 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
309 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
311 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
312 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
314 CloseHandle(tmpHandle);
317 static void destroy_pipe (HANDLE pipe[2]) {
318 if (pipe[0] != INVALID_HANDLE_VALUE) {
319 CloseHandle(pipe[0]);
320 pipe[0] = INVALID_HANDLE_VALUE;
322 if (pipe[1] != INVALID_HANDLE_VALUE) {
323 CloseHandle(pipe[1]);
324 pipe[1] = INVALID_HANDLE_VALUE;
328 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
330 DWORD currentProcId = 0;
331 GetWindowThreadProcessId(hwnd, ¤tProcId);
332 if (currentProcId == (DWORD)procId)
333 PostMessage(hwnd, WM_CLOSE, 0, 0);
340 SystemExec::make_envp() {
341 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
345 SystemExec::make_wargs(char **a) {
346 std::string wa = cmd;
347 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
348 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
350 while (tmp && *tmp) {
356 w_args = strdup(wa.c_str());
360 SystemExec::make_argp(std::string args) {
361 std::string wa = cmd;
362 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
363 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
366 w_args = strdup(wa.c_str());
370 SystemExec::terminate ()
372 ::pthread_mutex_lock(&write_lock);
375 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
376 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
379 TerminateProcess(pid->hProcess, 0xf291);
381 CloseHandle(pid->hThread);
382 CloseHandle(pid->hProcess);
383 destroy_pipe(stdinP);
384 destroy_pipe(stdoutP);
385 destroy_pipe(stderrP);
389 ::pthread_mutex_unlock(&write_lock);
393 SystemExec::wait (int options)
395 while (is_running()) {
396 WaitForSingleObject(pid->hProcess, INFINITE);
403 SystemExec::is_running ()
405 return pid?true:false;
409 SystemExec::start (int stderr_mode)
411 char* working_dir = 0;
413 if (pid) { return 0; }
415 pid = new PROCESS_INFORMATION;
416 memset(pid, 0, sizeof(PROCESS_INFORMATION));
418 create_pipe(stdinP, true);
419 create_pipe(stdoutP, false);
421 if (stderr_mode == 2) {
422 /* merge stout & stderr */
423 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
424 } else if (stderr_mode == 1) {
425 //TODO read/flush this pipe or close it...
426 create_pipe(stderrP, false);
428 //TODO: keep stderr of this process mode.
431 bool success = false;
432 STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
433 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
434 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
436 STARTF_USESTDHANDLES,
438 stdinP[0], stdoutP[1], stderrP[1]
441 success = CreateProcess(0, w_args,
442 0, 0, /* bInheritHandles = */ TRUE,
443 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
448 if (stdinP[0] != INVALID_HANDLE_VALUE) {
449 CloseHandle(stdinP[0]);
450 stdinP[0] = INVALID_HANDLE_VALUE;
452 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
453 CloseHandle(stdoutP[1]);
454 stdoutP[1] = INVALID_HANDLE_VALUE;
456 if (stderrP[1] != INVALID_HANDLE_VALUE) {
457 CloseHandle(stderrP[1]);
458 stderrP[1] = INVALID_HANDLE_VALUE;
462 CloseHandle(pid->hThread);
463 CloseHandle(pid->hProcess);
464 destroy_pipe(stdinP);
465 destroy_pipe(stdoutP);
466 destroy_pipe(stderrP);
472 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
484 SystemExec::output_interposer()
488 #if 0 // untested code to set up nonblocking
490 ioctlsocket(stdoutP[0], FIONBIO, &l);
493 #if 0 // for non-blocking pipes..
494 DWORD bytesAvail = 0;
495 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
496 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
498 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
499 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) break;
500 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
502 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
504 Terminated();/* EMIT SIGNAL */
508 SystemExec::close_stdin()
510 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
511 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
513 destroy_pipe(stdinP);
517 SystemExec::write_to_stdin(std::string d, size_t len)
522 ::pthread_mutex_lock(&write_lock);
530 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
531 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
535 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
541 ::pthread_mutex_unlock(&write_lock);
546 /* end windows process */
548 /* UNIX/POSIX process */
550 extern char **environ;
552 SystemExec::make_envp() {
554 envp = (char **) calloc(1, sizeof(char*));
555 /* copy current environment */
556 for (i=0;environ[i];++i) {
557 envp[i] = strdup(environ[i]);
558 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
564 SystemExec::make_argp(std::string args) {
569 char *carg = strdup(args.c_str());
571 argp = (char **) malloc((argn + 1) * sizeof(char *));
572 if (argp == (char **) 0) {
577 argp[0] = strdup(cmd.c_str());
579 /* TODO: quotations and escapes
580 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
582 * It's actually not needed. All relevant invocations specify 'argp' directly.
583 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
584 * nor arguments with white-space.
586 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
589 argp[argn++] = strdup(cp1);
591 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
595 argp[argn++] = strdup(cp1);
596 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
598 argp[argn] = (char *) 0;
605 SystemExec::terminate ()
607 ::pthread_mutex_lock(&write_lock);
609 /* close stdin in an attempt to get the child to exit cleanly.
620 /* if pid is non-zero, the child task is still executing (i.e. it did
621 * not exit in response to stdin being closed). try to kill it.
625 ::kill(pid, SIGTERM);
631 /* if pid is non-zero, the child task is STILL executing after being
632 * sent SIGTERM. Act tough ... send SIGKILL
636 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
637 ::kill(pid, SIGKILL);
641 if (thread_active) pthread_join(thread_id_tt, NULL);
642 thread_active = false;
643 ::pthread_mutex_unlock(&write_lock);
647 SystemExec::wait (int options)
652 if (pid==0) return -1;
654 ret = waitpid (pid, &status, options);
657 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
662 if (errno == ECHILD) {
663 /* no currently running children, reset pid */
666 } /* else the process is still running */
672 SystemExec::is_running ()
675 if (pid==0) return false;
676 if (::waitpid(pid, &status, WNOHANG)==0) return true;
681 SystemExec::start (int stderr_mode)
684 return 0; // mmh what to return here?
688 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
689 /* Something unexpected went wrong creating a pipe. */
703 /* check if execve was successful. */
707 ssize_t n = ::read(pok[0], &buf, 1 );
709 /* child process returned from execve */
718 } else if ( n==-1 ) {
719 if ( errno==EAGAIN || errno==EINTR )
725 /* child started successfully */
728 /* use fork for output-interposer
729 * it will run in a separated process
731 /* catch stdout thread */
739 /* 2nd child process - catch stdout */
748 #else /* use pthread */
751 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
760 return 0; /* all systems go - return to main */
763 /* child process - exec external process */
765 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
768 if (pin[0] != STDIN_FILENO) {
769 ::dup2(pin[0], STDIN_FILENO);
773 if (pout[1] != STDOUT_FILENO) {
774 ::dup2(pout[1], STDOUT_FILENO);
777 if (stderr_mode == 2) {
778 /* merge STDERR into output */
779 if (pout[1] != STDERR_FILENO) {
780 ::dup2(pout[1], STDERR_FILENO);
782 } else if (stderr_mode == 1) {
784 ::close(STDERR_FILENO);
789 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
798 /* chdir to executable dir */
800 directory = strdup(cmd.c_str());
801 if (strrchr(directory, '/') != (char *) 0) {
808 sigset(SIGPIPE, SIG_DFL);
810 signal(SIGPIPE, SIG_DFL);
813 int good_fds[1] = { -1 };
814 close_allv(good_fds);
816 ::execve(argp[0], argp, envp);
817 /* if we reach here something went wrong.. */
819 (void) ::write(pok[1], &buf, 1 );
826 SystemExec::output_interposer()
833 ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
835 for (;fcntl(rfd, F_GETFL)!=-1;) {
836 r = read(rfd, buf, sizeof(buf));
837 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
845 std::string rv = std::string(buf,r); // TODO: check allocation strategy
846 ReadStdout(rv, r);/* EMIT SIGNAL */
848 Terminated();/* EMIT SIGNAL */
852 SystemExec::close_stdin()
854 if (pin[1]<0) return;
862 SystemExec::write_to_stdin(std::string d, size_t len)
867 ::pthread_mutex_lock(&write_lock);
876 r=::write(pin[1], data+c, len-c);
877 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
881 if ((size_t) r != (len-c)) {
882 ::pthread_mutex_unlock(&write_lock);
890 ::pthread_mutex_unlock(&write_lock);
894 #endif // end UNIX process