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>
46 #include <glibmm/miscutils.h>
50 #include "pbd/file_utils.h"
51 #include "pbd/search_path.h"
52 #include "pbd/system_exec.h"
57 static void * interposer_thread (void *arg);
59 #ifndef PLATFORM_WINDOWS /* POSIX Process only */
60 static void close_fd (int& fd) { if (fd >= 0) ::close (fd); fd = -1; }
63 #if (!defined PLATFORM_WINDOWS && defined NO_VFORK)
65 * This function was part of libasyncns.
67 * Copyright 2005-2008 Lennart Poettering
69 static int close_allv(const int except_fds[]) {
79 if ((d = opendir("/proc/self/fd"))) {
82 while ((de = readdir(d))) {
88 if (de->d_name[0] == '.')
92 l = strtol(de->d_name, &e, 10);
93 if (errno != 0 || !e || *e) {
101 if ((long) fd != l) {
114 for (i = 0; except_fds[i] >= 0; i++)
115 if (except_fds[i] == fd) {
139 if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
142 for (fd = 0; fd < (int) rl.rlim_max; fd++) {
148 for (i = 0; except_fds[i] >= 0; i++)
149 if (except_fds[i] == fd)
152 if (close(fd) < 0 && errno != EBADF)
158 #endif /* not on windows, nor vfork */
163 pthread_mutex_init(&write_lock, NULL);
169 #ifdef PLATFORM_WINDOWS
170 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
171 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
172 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
176 SystemExec::SystemExec (std::string c, std::string a)
186 SystemExec::SystemExec (std::string c, char **a)
191 #ifdef PLATFORM_WINDOWS
197 SystemExec::SystemExec (std::string command, const std::map<char, std::string> subs)
200 make_argp_escaped(command, subs);
202 if (find_file (Searchpath (Glib::getenv ("PATH")), argp[0], cmd)) {
203 // argp[0] exists in $PATH` - set it to the actual path where it was found
205 argp[0] = strdup(cmd.c_str ());
207 // else argp[0] not found in path - leave it as-is, it might be an absolute path
209 // Glib::find_program_in_path () is only available in Glib >= 2.28
210 // cmd = Glib::find_program_in_path (argp[0]);
216 SystemExec::make_argp_escaped(std::string command, const std::map<char, std::string> subs)
222 std::string arg = "";
224 argp = (char **) malloc(sizeof(char *));
226 for (i = 0; i <= command.length(); i++) { // include terminating '\0'
227 char c = command.c_str()[i];
232 // still in quotes - just copy
237 c = command.c_str()[++i];
238 if (c == '%' || c == '\0') {
239 // "%%", "%" at end-of-string => "%"
242 // search subs for string to substitute for char
243 std::map<char, std::string>::const_iterator s = subs.find(c);
244 if (s != subs.end()) {
245 // found substitution
248 // not a valid substitution, just copy
255 c = command.c_str()[++i];
258 case '"' : arg += c; break; // "\\", "\" at end-of-string => "\"
260 case '\\': arg += '\\'; break;
261 default : arg += '\\'; arg += c; break;
270 if (arg.length() > 0) {
271 // if there wasn't already a space or tab, start a new parameter
272 argp = (char **) realloc(argp, (n + 2) * sizeof(char *));
273 argp[n++] = strdup (arg.c_str());
285 SystemExec::~SystemExec ()
289 for (int i=0;envp[i];++i) {
295 for (int i=0;argp[i];++i) {
300 #ifdef PLATFORM_WINDOWS
301 if (w_args) free(w_args);
303 pthread_mutex_destroy(&write_lock);
307 interposer_thread (void *arg) {
308 SystemExec *sex = static_cast<SystemExec *>(arg);
309 sex->output_interposer();
314 #ifdef PLATFORM_WINDOWS /* Windows Process */
316 /* HELPER FUNCTIONS */
318 static void create_pipe (HANDLE *pipe, bool in) {
319 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
322 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
323 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
325 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
326 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
328 CloseHandle(tmpHandle);
331 static void destroy_pipe (HANDLE pipe[2]) {
332 if (pipe[0] != INVALID_HANDLE_VALUE) {
333 CloseHandle(pipe[0]);
334 pipe[0] = INVALID_HANDLE_VALUE;
336 if (pipe[1] != INVALID_HANDLE_VALUE) {
337 CloseHandle(pipe[1]);
338 pipe[1] = INVALID_HANDLE_VALUE;
342 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
344 DWORD currentProcId = 0;
345 GetWindowThreadProcessId(hwnd, ¤tProcId);
346 if (currentProcId == (DWORD)procId)
347 PostMessage(hwnd, WM_CLOSE, 0, 0);
354 SystemExec::make_envp() {
355 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
359 SystemExec::make_wargs(char **a) {
360 std::string wa = cmd;
361 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
362 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
364 while (tmp && *tmp) {
367 if (strlen(*tmp) > 0 && (*tmp)[strlen(*tmp) - 1] == '\\') {
373 w_args = strdup(wa.c_str());
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(), '/', '\\' );
383 w_args = strdup(wa.c_str());
387 SystemExec::terminate ()
389 ::pthread_mutex_lock(&write_lock);
395 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
396 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
399 TerminateProcess(pid->hProcess, 0xf291);
401 CloseHandle(pid->hThread);
402 CloseHandle(pid->hProcess);
403 destroy_pipe(stdinP);
404 destroy_pipe(stdoutP);
405 destroy_pipe(stderrP);
409 ::pthread_mutex_unlock(&write_lock);
413 SystemExec::wait (int options)
415 while (is_running()) {
416 WaitForSingleObject(pid->hProcess, 40);
422 SystemExec::is_running ()
424 if (!pid) return false;
426 if (GetExitCodeProcess(pid->hProcess, &exit_code)) {
427 if (exit_code == STILL_ACTIVE) return true;
433 SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
435 char* working_dir = 0;
437 if (pid) { return 0; }
439 pid = new PROCESS_INFORMATION;
440 memset(pid, 0, sizeof(PROCESS_INFORMATION));
442 create_pipe(stdinP, true);
443 create_pipe(stdoutP, false);
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);
452 //TODO: keep stderr of this process mode.
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,
460 STARTF_USESTDHANDLES,
462 stdinP[0], stdoutP[1], stderrP[1]
465 success = CreateProcess(0, w_args,
466 0, 0, /* bInheritHandles = */ TRUE,
467 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
472 if (stdinP[0] != INVALID_HANDLE_VALUE) {
473 CloseHandle(stdinP[0]);
474 stdinP[0] = INVALID_HANDLE_VALUE;
476 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
477 CloseHandle(stdoutP[1]);
478 stdoutP[1] = INVALID_HANDLE_VALUE;
480 if (stderrP[1] != INVALID_HANDLE_VALUE) {
481 CloseHandle(stderrP[1]);
482 stderrP[1] = INVALID_HANDLE_VALUE;
486 CloseHandle(pid->hThread);
487 CloseHandle(pid->hProcess);
488 destroy_pipe(stdinP);
489 destroy_pipe(stdoutP);
490 destroy_pipe(stderrP);
496 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
508 SystemExec::output_interposer()
512 #if 0 // untested code to set up nonblocking
514 ioctlsocket(stdoutP[0], FIONBIO, &l);
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;}
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;
528 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
530 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
532 Terminated();/* EMIT SIGNAL */
536 SystemExec::close_stdin()
538 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
539 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
541 destroy_pipe(stdinP);
545 SystemExec::write_to_stdin(std::string d, size_t len)
550 ::pthread_mutex_lock(&write_lock);
558 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
559 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
563 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
569 ::pthread_mutex_unlock(&write_lock);
574 /* end windows process */
576 /* UNIX/POSIX process */
578 extern char **environ;
580 SystemExec::make_envp() {
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*));
592 SystemExec::make_argp(std::string args) {
597 char *carg = strdup(args.c_str());
599 argp = (char **) malloc((argn + 1) * sizeof(char *));
600 if (argp == (char **) 0) {
605 argp[0] = strdup(cmd.c_str());
607 /* TODO: quotations and escapes
608 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
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.
614 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
617 argp[argn++] = strdup(cp1);
619 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
623 argp[argn++] = strdup(cp1);
624 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
626 argp[argn] = (char *) 0;
633 SystemExec::terminate ()
635 ::pthread_mutex_lock(&write_lock);
637 /* close stdin in an attempt to get the child to exit cleanly.
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.
653 ::kill(pid, SIGTERM);
659 /* if pid is non-zero, the child task is STILL executing after being
660 * sent SIGTERM. Act tough ... send SIGKILL
664 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
665 ::kill(pid, SIGKILL);
669 if (thread_active) pthread_join(thread_id_tt, NULL);
670 thread_active = false;
672 ::pthread_mutex_unlock(&write_lock);
676 SystemExec::wait (int options)
681 if (pid==0) return -1;
683 ret = waitpid (pid, &status, options);
686 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
691 if (errno == ECHILD) {
692 /* no currently running children, reset pid */
695 } /* else the process is still running */
701 SystemExec::is_running ()
704 if (pid==0) return false;
705 if (::waitpid(pid, &status, WNOHANG)==0) return true;
710 SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
713 return 0; // mmh what to return here?
717 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
718 /* Something unexpected went wrong creating a pipe. */
736 /* check if execve was successful. */
740 ssize_t n = ::read(pok[0], &buf, 1 );
742 /* child process returned from execve */
751 } else if ( n==-1 ) {
752 if ( errno==EAGAIN || errno==EINTR )
758 /* child started successfully */
762 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
770 return 0; /* all systems go - return to main */
774 /* child process - exec external process */
776 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
779 if (pin[0] != STDIN_FILENO) {
780 ::dup2(pin[0], STDIN_FILENO);
784 if (pout[1] != STDOUT_FILENO) {
785 ::dup2(pout[1], STDOUT_FILENO);
788 if (stderr_mode == 2) {
789 /* merge STDERR into output */
790 if (pout[1] != STDERR_FILENO) {
791 ::dup2(pout[1], STDERR_FILENO);
793 } else if (stderr_mode == 1) {
795 ::close(STDERR_FILENO);
800 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
809 sigset(SIGPIPE, SIG_DFL);
811 signal(SIGPIPE, SIG_DFL);
813 if (!vfork_exec_wrapper) {
814 error << _("Cannot start external process, no vfork wrapper") << endmsg;
818 int good_fds[2] = { pok[1], -1 };
819 close_allv(good_fds);
821 ::execve(argp[0], argp, envp);
822 /* if we reach here something went wrong.. */
824 (void) ::write(pok[1], &buf, 1 );
830 /* XXX this should be done before vfork()
831 * calling malloc here only increases the time vfork() blocks
834 for (int i=0;argp[i];++i) { argn++; }
835 char **argx = (char **) malloc((argn + 10) * sizeof(char *));
836 argx[0] = strdup(vfork_exec_wrapper); // XXX
838 #define FDARG(NUM, FDN) \
839 argx[NUM] = (char*) calloc(6, sizeof(char)); snprintf(argx[NUM], 6, "%d", FDN);
847 FDARG(7, stderr_mode)
850 for (int i=0;argp[i];++i) {
855 ::execve(argx[0], argx, envp);
857 /* if we reach here something went wrong.. */
859 (void) ::write(pok[1], &buf, 1 );
867 SystemExec::output_interposer()
874 ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
876 for (;fcntl(rfd, F_GETFL)!=-1;) {
877 r = read(rfd, buf, sizeof(buf));
878 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
885 int rv = select(1, &rfds, NULL, NULL, &tv);
895 std::string rv = std::string(buf,r); // TODO: check allocation strategy
896 ReadStdout(rv, r);/* EMIT SIGNAL */
898 Terminated();/* EMIT SIGNAL */
902 SystemExec::close_stdin()
904 if (pin[1]<0) return;
912 SystemExec::write_to_stdin(std::string d, size_t len)
917 ::pthread_mutex_lock(&write_lock);
926 r=::write(pin[1], data+c, len-c);
927 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
931 if ((size_t) r != (len-c)) {
932 ::pthread_mutex_unlock(&write_lock);
940 ::pthread_mutex_unlock(&write_lock);
944 #endif // end UNIX process