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;
177 SystemExec::SystemExec (std::string c, std::string a)
187 SystemExec::SystemExec (std::string c, char **a)
192 #ifdef PLATFORM_WINDOWS
198 SystemExec::SystemExec (std::string command, const std::map<char, std::string> subs)
201 make_argp_escaped(command, subs);
203 #ifdef PLATFORM_WINDOWS
205 for (int i = 0; argp[i]; ++i) {
206 if (!wa.empty ()) wa += " ";
207 wa += '"' + argp[i] + '"';
209 w_args = strdup(wa.c_str());
211 if (find_file (Searchpath (Glib::getenv ("PATH")), argp[0], cmd)) {
212 // argp[0] exists in $PATH` - set it to the actual path where it was found
214 argp[0] = strdup(cmd.c_str ());
216 // else argp[0] not found in path - leave it as-is, it might be an absolute path
218 // Glib::find_program_in_path () is only available in Glib >= 2.28
219 // cmd = Glib::find_program_in_path (argp[0]);
225 SystemExec::make_argp_escaped(std::string command, const std::map<char, std::string> subs)
231 std::string arg = "";
233 argp = (char **) malloc(sizeof(char *));
235 for (i = 0; i <= command.length(); i++) { // include terminating '\0'
236 char c = command.c_str()[i];
241 // still in quotes - just copy
246 c = command.c_str()[++i];
247 if (c == '%' || c == '\0') {
248 // "%%", "%" at end-of-string => "%"
251 // search subs for string to substitute for char
252 std::map<char, std::string>::const_iterator s = subs.find(c);
253 if (s != subs.end()) {
254 // found substitution
257 // not a valid substitution, just copy
264 c = command.c_str()[++i];
267 case '"' : arg += c; break; // "\\", "\" at end-of-string => "\"
269 case '\\': arg += '\\'; break;
270 default : arg += '\\'; arg += c; break;
279 if (arg.length() > 0) {
280 // if there wasn't already a space or tab, start a new parameter
281 argp = (char **) realloc(argp, (n + 2) * sizeof(char *));
282 argp[n++] = strdup (arg.c_str());
294 SystemExec::~SystemExec ()
298 for (int i=0;envp[i];++i) {
304 for (int i=0;argp[i];++i) {
309 #ifdef PLATFORM_WINDOWS
310 if (w_args) free(w_args);
312 pthread_mutex_destroy(&write_lock);
316 interposer_thread (void *arg) {
317 SystemExec *sex = static_cast<SystemExec *>(arg);
318 sex->output_interposer();
324 SystemExec::to_s () const
328 for (int i = 0; argp[i]; ++i) {
329 out << argp[i] << " ";
335 #ifdef PLATFORM_WINDOWS /* Windows Process */
337 /* HELPER FUNCTIONS */
339 static void create_pipe (HANDLE *pipe, bool in) {
340 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
343 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
344 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
346 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
347 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
349 CloseHandle(tmpHandle);
352 static void destroy_pipe (HANDLE pipe[2]) {
353 if (pipe[0] != INVALID_HANDLE_VALUE) {
354 CloseHandle(pipe[0]);
355 pipe[0] = INVALID_HANDLE_VALUE;
357 if (pipe[1] != INVALID_HANDLE_VALUE) {
358 CloseHandle(pipe[1]);
359 pipe[1] = INVALID_HANDLE_VALUE;
363 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
365 DWORD currentProcId = 0;
366 GetWindowThreadProcessId(hwnd, ¤tProcId);
367 if (currentProcId == (DWORD)procId)
368 PostMessage(hwnd, WM_CLOSE, 0, 0);
375 SystemExec::make_envp() {
376 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
380 SystemExec::make_wargs(char **a) {
381 std::string wa = cmd;
382 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
383 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
385 while (tmp && *tmp) {
388 if (strlen(*tmp) > 0 && (*tmp)[strlen(*tmp) - 1] == '\\') {
394 w_args = strdup(wa.c_str());
398 SystemExec::make_argp(std::string args) {
399 std::string wa = cmd;
400 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
401 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
404 w_args = strdup(wa.c_str());
408 SystemExec::terminate ()
410 ::pthread_mutex_lock(&write_lock);
416 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
417 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
420 TerminateProcess(pid->hProcess, 0xf291);
422 CloseHandle(pid->hThread);
423 CloseHandle(pid->hProcess);
424 destroy_pipe(stdinP);
425 destroy_pipe(stdoutP);
426 destroy_pipe(stderrP);
430 ::pthread_mutex_unlock(&write_lock);
434 SystemExec::wait (int options)
436 while (is_running()) {
437 WaitForSingleObject(pid->hProcess, 40);
443 SystemExec::is_running ()
445 if (!pid) return false;
447 if (GetExitCodeProcess(pid->hProcess, &exit_code)) {
448 if (exit_code == STILL_ACTIVE) return true;
454 SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
456 char* working_dir = 0;
458 if (pid) { return 0; }
460 pid = new PROCESS_INFORMATION;
461 memset(pid, 0, sizeof(PROCESS_INFORMATION));
463 create_pipe(stdinP, true);
464 create_pipe(stdoutP, false);
466 if (stderr_mode == 2) {
467 /* merge stout & stderr */
468 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
469 } else if (stderr_mode == 1) {
470 //TODO read/flush this pipe or close it...
471 create_pipe(stderrP, false);
473 //TODO: keep stderr of this process mode.
476 bool success = false;
477 STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
478 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
479 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
481 STARTF_USESTDHANDLES,
483 stdinP[0], stdoutP[1], stderrP[1]
486 success = CreateProcess(0, w_args,
487 0, 0, /* bInheritHandles = */ TRUE,
488 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
493 if (stdinP[0] != INVALID_HANDLE_VALUE) {
494 CloseHandle(stdinP[0]);
495 stdinP[0] = INVALID_HANDLE_VALUE;
497 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
498 CloseHandle(stdoutP[1]);
499 stdoutP[1] = INVALID_HANDLE_VALUE;
501 if (stderrP[1] != INVALID_HANDLE_VALUE) {
502 CloseHandle(stderrP[1]);
503 stderrP[1] = INVALID_HANDLE_VALUE;
507 CloseHandle(pid->hThread);
508 CloseHandle(pid->hProcess);
509 destroy_pipe(stdinP);
510 destroy_pipe(stdoutP);
511 destroy_pipe(stderrP);
517 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
529 SystemExec::output_interposer()
533 #if 0 // untested code to set up nonblocking
535 ioctlsocket(stdoutP[0], FIONBIO, &l);
538 #if 0 // for non-blocking pipes..
539 DWORD bytesAvail = 0;
540 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
541 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
543 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
544 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) {
545 DWORD err = GetLastError();
546 if (err == ERROR_IO_PENDING) continue;
549 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
551 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
553 Terminated();/* EMIT SIGNAL */
558 SystemExec::close_stdin()
560 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
561 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
563 destroy_pipe(stdinP);
567 SystemExec::write_to_stdin(std::string d, size_t len)
572 ::pthread_mutex_lock(&write_lock);
580 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
581 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
585 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
591 ::pthread_mutex_unlock(&write_lock);
596 /* end windows process */
598 /* UNIX/POSIX process */
600 extern char **environ;
602 SystemExec::make_envp() {
604 envp = (char **) calloc(1, sizeof(char*));
605 /* copy current environment */
606 for (i=0;environ[i];++i) {
607 envp[i] = strdup(environ[i]);
608 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
614 SystemExec::make_argp(std::string args) {
619 char *carg = strdup(args.c_str());
621 argp = (char **) malloc((argn + 1) * sizeof(char *));
622 if (argp == (char **) 0) {
627 argp[0] = strdup(cmd.c_str());
629 /* TODO: quotations and escapes
630 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
632 * It's actually not needed. All relevant invocations specify 'argp' directly.
633 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
634 * nor arguments with white-space.
636 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
639 argp[argn++] = strdup(cp1);
641 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
645 argp[argn++] = strdup(cp1);
646 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
648 argp[argn] = (char *) 0;
655 SystemExec::terminate ()
657 ::pthread_mutex_lock(&write_lock);
659 /* close stdin in an attempt to get the child to exit cleanly.
670 /* if pid is non-zero, the child task is still executing (i.e. it did
671 * not exit in response to stdin being closed). try to kill it.
675 ::kill(pid, SIGTERM);
681 /* if pid is non-zero, the child task is STILL executing after being
682 * sent SIGTERM. Act tough ... send SIGKILL
686 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
687 ::kill(pid, SIGKILL);
691 if (thread_active) pthread_join(thread_id_tt, NULL);
692 thread_active = false;
694 ::pthread_mutex_unlock(&write_lock);
698 SystemExec::wait (int options)
703 if (pid==0) return -1;
705 ret = waitpid (pid, &status, options);
708 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
713 if (errno == ECHILD) {
714 /* no currently running children, reset pid */
717 } /* else the process is still running */
723 SystemExec::is_running ()
726 if (pid==0) return false;
727 if (::waitpid(pid, &status, WNOHANG)==0) return true;
732 SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
735 return 0; // mmh what to return here?
739 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
740 /* Something unexpected went wrong creating a pipe. */
758 /* check if execve was successful. */
762 ssize_t n = ::read(pok[0], &buf, 1 );
764 /* child process returned from execve */
773 } else if ( n==-1 ) {
774 if ( errno==EAGAIN || errno==EINTR )
780 /* child started successfully */
784 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
792 return 0; /* all systems go - return to main */
796 /* child process - exec external process */
798 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
801 if (pin[0] != STDIN_FILENO) {
802 ::dup2(pin[0], STDIN_FILENO);
806 if (pout[1] != STDOUT_FILENO) {
807 ::dup2(pout[1], STDOUT_FILENO);
810 if (stderr_mode == 2) {
811 /* merge STDERR into output */
812 if (pout[1] != STDERR_FILENO) {
813 ::dup2(pout[1], STDERR_FILENO);
815 } else if (stderr_mode == 1) {
817 ::close(STDERR_FILENO);
822 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
831 sigset(SIGPIPE, SIG_DFL);
833 signal(SIGPIPE, SIG_DFL);
835 if (!vfork_exec_wrapper) {
836 error << _("Cannot start external process, no vfork wrapper") << endmsg;
840 int good_fds[2] = { pok[1], -1 };
841 close_allv(good_fds);
843 ::execve(argp[0], argp, envp);
844 /* if we reach here something went wrong.. */
846 (void) ::write(pok[1], &buf, 1 );
852 /* XXX this should be done before vfork()
853 * calling malloc here only increases the time vfork() blocks
856 for (int i=0;argp[i];++i) { argn++; }
857 char **argx = (char **) malloc((argn + 10) * sizeof(char *));
858 argx[0] = strdup(vfork_exec_wrapper); // XXX
860 #define FDARG(NUM, FDN) \
861 argx[NUM] = (char*) calloc(6, sizeof(char)); snprintf(argx[NUM], 6, "%d", FDN);
869 FDARG(7, stderr_mode)
872 for (int i=0;argp[i];++i) {
877 ::execve(argx[0], argx, envp);
879 /* if we reach here something went wrong.. */
881 (void) ::write(pok[1], &buf, 1 );
889 SystemExec::output_interposer()
896 ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
898 for (;fcntl(rfd, F_GETFL)!=-1;) {
899 r = read(rfd, buf, sizeof(buf));
900 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
907 int rv = select(1, &rfds, NULL, NULL, &tv);
917 std::string rv = std::string(buf,r); // TODO: check allocation strategy
918 ReadStdout(rv, r);/* EMIT SIGNAL */
920 Terminated();/* EMIT SIGNAL */
925 SystemExec::close_stdin()
927 if (pin[1]<0) return;
935 SystemExec::write_to_stdin(std::string d, size_t len)
940 ::pthread_mutex_lock(&write_lock);
949 r=::write(pin[1], data+c, len-c);
950 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
954 if ((size_t) r != (len-c)) {
955 ::pthread_mutex_unlock(&write_lock);
963 ::pthread_mutex_unlock(&write_lock);
967 #endif // end UNIX process