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());
286 SystemExec::GetString ()
290 for (int i = 0; argp[i]; ++i) {
297 SystemExec::~SystemExec ()
301 for (int i=0;envp[i];++i) {
307 for (int i=0;argp[i];++i) {
312 #ifdef PLATFORM_WINDOWS
313 if (w_args) free(w_args);
315 pthread_mutex_destroy(&write_lock);
319 interposer_thread (void *arg) {
320 SystemExec *sex = static_cast<SystemExec *>(arg);
321 sex->output_interposer();
326 #ifdef PLATFORM_WINDOWS /* Windows Process */
328 /* HELPER FUNCTIONS */
330 static void create_pipe (HANDLE *pipe, bool in) {
331 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
334 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
335 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
337 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
338 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
340 CloseHandle(tmpHandle);
343 static void destroy_pipe (HANDLE pipe[2]) {
344 if (pipe[0] != INVALID_HANDLE_VALUE) {
345 CloseHandle(pipe[0]);
346 pipe[0] = INVALID_HANDLE_VALUE;
348 if (pipe[1] != INVALID_HANDLE_VALUE) {
349 CloseHandle(pipe[1]);
350 pipe[1] = INVALID_HANDLE_VALUE;
354 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
356 DWORD currentProcId = 0;
357 GetWindowThreadProcessId(hwnd, ¤tProcId);
358 if (currentProcId == (DWORD)procId)
359 PostMessage(hwnd, WM_CLOSE, 0, 0);
366 SystemExec::make_envp() {
367 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
371 SystemExec::make_wargs(char **a) {
372 std::string wa = cmd;
373 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
374 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
376 while (tmp && *tmp) {
379 if (strlen(*tmp) > 0 && (*tmp)[strlen(*tmp) - 1] == '\\') {
385 w_args = strdup(wa.c_str());
389 SystemExec::make_argp(std::string args) {
390 std::string wa = cmd;
391 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
392 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
395 w_args = strdup(wa.c_str());
399 SystemExec::terminate ()
401 ::pthread_mutex_lock(&write_lock);
407 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
408 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
411 TerminateProcess(pid->hProcess, 0xf291);
413 CloseHandle(pid->hThread);
414 CloseHandle(pid->hProcess);
415 destroy_pipe(stdinP);
416 destroy_pipe(stdoutP);
417 destroy_pipe(stderrP);
421 ::pthread_mutex_unlock(&write_lock);
425 SystemExec::wait (int options)
427 while (is_running()) {
428 WaitForSingleObject(pid->hProcess, 40);
434 SystemExec::is_running ()
436 if (!pid) return false;
438 if (GetExitCodeProcess(pid->hProcess, &exit_code)) {
439 if (exit_code == STILL_ACTIVE) return true;
445 SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
447 char* working_dir = 0;
449 if (pid) { return 0; }
451 pid = new PROCESS_INFORMATION;
452 memset(pid, 0, sizeof(PROCESS_INFORMATION));
454 create_pipe(stdinP, true);
455 create_pipe(stdoutP, false);
457 if (stderr_mode == 2) {
458 /* merge stout & stderr */
459 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
460 } else if (stderr_mode == 1) {
461 //TODO read/flush this pipe or close it...
462 create_pipe(stderrP, false);
464 //TODO: keep stderr of this process mode.
467 bool success = false;
468 STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
469 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
470 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
472 STARTF_USESTDHANDLES,
474 stdinP[0], stdoutP[1], stderrP[1]
477 success = CreateProcess(0, w_args,
478 0, 0, /* bInheritHandles = */ TRUE,
479 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
484 if (stdinP[0] != INVALID_HANDLE_VALUE) {
485 CloseHandle(stdinP[0]);
486 stdinP[0] = INVALID_HANDLE_VALUE;
488 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
489 CloseHandle(stdoutP[1]);
490 stdoutP[1] = INVALID_HANDLE_VALUE;
492 if (stderrP[1] != INVALID_HANDLE_VALUE) {
493 CloseHandle(stderrP[1]);
494 stderrP[1] = INVALID_HANDLE_VALUE;
498 CloseHandle(pid->hThread);
499 CloseHandle(pid->hProcess);
500 destroy_pipe(stdinP);
501 destroy_pipe(stdoutP);
502 destroy_pipe(stderrP);
508 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
520 SystemExec::output_interposer()
524 #if 0 // untested code to set up nonblocking
526 ioctlsocket(stdoutP[0], FIONBIO, &l);
529 #if 0 // for non-blocking pipes..
530 DWORD bytesAvail = 0;
531 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
532 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
534 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
535 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) {
536 DWORD err = GetLastError();
537 if (err == ERROR_IO_PENDING) continue;
540 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
542 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
544 Terminated();/* EMIT SIGNAL */
549 SystemExec::close_stdin()
551 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
552 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
554 destroy_pipe(stdinP);
558 SystemExec::write_to_stdin(std::string d, size_t len)
563 ::pthread_mutex_lock(&write_lock);
571 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
572 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
576 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
582 ::pthread_mutex_unlock(&write_lock);
587 /* end windows process */
589 /* UNIX/POSIX process */
591 extern char **environ;
593 SystemExec::make_envp() {
595 envp = (char **) calloc(1, sizeof(char*));
596 /* copy current environment */
597 for (i=0;environ[i];++i) {
598 envp[i] = strdup(environ[i]);
599 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
605 SystemExec::make_argp(std::string args) {
610 char *carg = strdup(args.c_str());
612 argp = (char **) malloc((argn + 1) * sizeof(char *));
613 if (argp == (char **) 0) {
618 argp[0] = strdup(cmd.c_str());
620 /* TODO: quotations and escapes
621 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
623 * It's actually not needed. All relevant invocations specify 'argp' directly.
624 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
625 * nor arguments with white-space.
627 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
630 argp[argn++] = strdup(cp1);
632 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
636 argp[argn++] = strdup(cp1);
637 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
639 argp[argn] = (char *) 0;
646 SystemExec::terminate ()
648 ::pthread_mutex_lock(&write_lock);
650 /* close stdin in an attempt to get the child to exit cleanly.
661 /* if pid is non-zero, the child task is still executing (i.e. it did
662 * not exit in response to stdin being closed). try to kill it.
666 ::kill(pid, SIGTERM);
672 /* if pid is non-zero, the child task is STILL executing after being
673 * sent SIGTERM. Act tough ... send SIGKILL
677 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
678 ::kill(pid, SIGKILL);
682 if (thread_active) pthread_join(thread_id_tt, NULL);
683 thread_active = false;
685 ::pthread_mutex_unlock(&write_lock);
689 SystemExec::wait (int options)
694 if (pid==0) return -1;
696 ret = waitpid (pid, &status, options);
699 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
704 if (errno == ECHILD) {
705 /* no currently running children, reset pid */
708 } /* else the process is still running */
714 SystemExec::is_running ()
717 if (pid==0) return false;
718 if (::waitpid(pid, &status, WNOHANG)==0) return true;
723 SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
726 return 0; // mmh what to return here?
730 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
731 /* Something unexpected went wrong creating a pipe. */
749 /* check if execve was successful. */
753 ssize_t n = ::read(pok[0], &buf, 1 );
755 /* child process returned from execve */
764 } else if ( n==-1 ) {
765 if ( errno==EAGAIN || errno==EINTR )
771 /* child started successfully */
775 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
783 return 0; /* all systems go - return to main */
787 /* child process - exec external process */
789 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
792 if (pin[0] != STDIN_FILENO) {
793 ::dup2(pin[0], STDIN_FILENO);
797 if (pout[1] != STDOUT_FILENO) {
798 ::dup2(pout[1], STDOUT_FILENO);
801 if (stderr_mode == 2) {
802 /* merge STDERR into output */
803 if (pout[1] != STDERR_FILENO) {
804 ::dup2(pout[1], STDERR_FILENO);
806 } else if (stderr_mode == 1) {
808 ::close(STDERR_FILENO);
813 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
822 sigset(SIGPIPE, SIG_DFL);
824 signal(SIGPIPE, SIG_DFL);
826 if (!vfork_exec_wrapper) {
827 error << _("Cannot start external process, no vfork wrapper") << endmsg;
831 int good_fds[2] = { pok[1], -1 };
832 close_allv(good_fds);
834 ::execve(argp[0], argp, envp);
835 /* if we reach here something went wrong.. */
837 (void) ::write(pok[1], &buf, 1 );
843 /* XXX this should be done before vfork()
844 * calling malloc here only increases the time vfork() blocks
847 for (int i=0;argp[i];++i) { argn++; }
848 char **argx = (char **) malloc((argn + 10) * sizeof(char *));
849 argx[0] = strdup(vfork_exec_wrapper); // XXX
851 #define FDARG(NUM, FDN) \
852 argx[NUM] = (char*) calloc(6, sizeof(char)); snprintf(argx[NUM], 6, "%d", FDN);
860 FDARG(7, stderr_mode)
863 for (int i=0;argp[i];++i) {
868 ::execve(argx[0], argx, envp);
870 /* if we reach here something went wrong.. */
872 (void) ::write(pok[1], &buf, 1 );
880 SystemExec::output_interposer()
887 ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
889 for (;fcntl(rfd, F_GETFL)!=-1;) {
890 r = read(rfd, buf, sizeof(buf));
891 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
898 int rv = select(1, &rfds, NULL, NULL, &tv);
908 std::string rv = std::string(buf,r); // TODO: check allocation strategy
909 ReadStdout(rv, r);/* EMIT SIGNAL */
911 Terminated();/* EMIT SIGNAL */
916 SystemExec::close_stdin()
918 if (pin[1]<0) return;
926 SystemExec::write_to_stdin(std::string d, size_t len)
931 ::pthread_mutex_lock(&write_lock);
940 r=::write(pin[1], data+c, len-c);
941 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
945 if ((size_t) r != (len-c)) {
946 ::pthread_mutex_unlock(&write_lock);
954 ::pthread_mutex_unlock(&write_lock);
958 #endif // end UNIX process