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
204 if (argp[0] && strlen (argp[0]) > 0) {
205 std::string wa = argp[0];
206 // only add quotes to command if required..
207 if (argp[0][0] != '"'
208 && argp[0][strlen(argp[0])-1] != '"'
209 && strchr(argp[0], ' ')) {
214 // ...but always quote all args
215 for (int i = 1; argp[i]; ++i) {
216 std::string tmp (argp[i]);
217 while (tmp.find("\"") != std::string::npos)
218 tmp.replace(tmp.find("\""), 1, "\\\"");
223 w_args = strdup(wa.c_str());
226 if (find_file (Searchpath (Glib::getenv ("PATH")), argp[0], cmd)) {
227 // argp[0] exists in $PATH` - set it to the actual path where it was found
229 argp[0] = strdup(cmd.c_str ());
231 // else argp[0] not found in path - leave it as-is, it might be an absolute path
233 // Glib::find_program_in_path () is only available in Glib >= 2.28
234 // cmd = Glib::find_program_in_path (argp[0]);
240 SystemExec::make_argp_escaped(std::string command, const std::map<char, std::string> subs)
246 std::string arg = "";
248 argp = (char **) malloc(sizeof(char *));
250 for (i = 0; i <= command.length(); i++) { // include terminating '\0'
251 char c = command.c_str()[i];
256 // still in quotes - just copy
261 c = command.c_str()[++i];
262 if (c == '%' || c == '\0') {
263 // "%%", "%" at end-of-string => "%"
266 // search subs for string to substitute for char
267 std::map<char, std::string>::const_iterator s = subs.find(c);
268 if (s != subs.end()) {
269 // found substitution
272 // not a valid substitution, just copy
279 c = command.c_str()[++i];
282 case '"' : arg += c; break; // "\\", "\" at end-of-string => "\"
284 case '\\': arg += '\\'; break;
285 default : arg += '\\'; arg += c; break;
294 if (arg.length() > 0) {
295 // if there wasn't already a space or tab, start a new parameter
296 argp = (char **) realloc(argp, (n + 2) * sizeof(char *));
297 argp[n++] = strdup (arg.c_str());
309 SystemExec::~SystemExec ()
313 for (int i=0;envp[i];++i) {
319 for (int i=0;argp[i];++i) {
324 #ifdef PLATFORM_WINDOWS
325 if (w_args) free(w_args);
327 pthread_mutex_destroy(&write_lock);
331 interposer_thread (void *arg) {
332 SystemExec *sex = static_cast<SystemExec *>(arg);
333 sex->output_interposer();
339 SystemExec::to_s () const
341 #ifdef PLATFORM_WINDOWS
342 return string (w_args ? w_args : "");
346 for (int i = 0; argp[i]; ++i) {
347 out << argp[i] << " ";
354 #ifdef PLATFORM_WINDOWS /* Windows Process */
356 /* HELPER FUNCTIONS */
358 static void create_pipe (HANDLE *pipe, bool in) {
359 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
362 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
363 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
365 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
366 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
368 CloseHandle(tmpHandle);
371 static void destroy_pipe (HANDLE pipe[2]) {
372 if (pipe[0] != INVALID_HANDLE_VALUE) {
373 CloseHandle(pipe[0]);
374 pipe[0] = INVALID_HANDLE_VALUE;
376 if (pipe[1] != INVALID_HANDLE_VALUE) {
377 CloseHandle(pipe[1]);
378 pipe[1] = INVALID_HANDLE_VALUE;
382 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
384 DWORD currentProcId = 0;
385 GetWindowThreadProcessId(hwnd, ¤tProcId);
386 if (currentProcId == (DWORD)procId)
387 PostMessage(hwnd, WM_CLOSE, 0, 0);
394 SystemExec::make_envp() {
395 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
399 SystemExec::make_wargs(char **a) {
400 std::string wa = cmd;
401 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
402 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
404 while (tmp && *tmp) {
407 if (strlen(*tmp) > 0 && (*tmp)[strlen(*tmp) - 1] == '\\') {
413 w_args = strdup(wa.c_str());
417 SystemExec::make_argp(std::string args) {
418 std::string wa = cmd;
419 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
420 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
423 w_args = strdup(wa.c_str());
427 SystemExec::terminate ()
429 ::pthread_mutex_lock(&write_lock);
435 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
436 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
439 TerminateProcess(pid->hProcess, 0xf291);
441 CloseHandle(pid->hThread);
442 CloseHandle(pid->hProcess);
443 destroy_pipe(stdinP);
444 destroy_pipe(stdoutP);
445 destroy_pipe(stderrP);
449 ::pthread_mutex_unlock(&write_lock);
453 SystemExec::wait (int options)
455 while (is_running()) {
456 WaitForSingleObject(pid->hProcess, 40);
462 SystemExec::is_running ()
464 if (!pid) return false;
466 if (GetExitCodeProcess(pid->hProcess, &exit_code)) {
467 if (exit_code == STILL_ACTIVE) return true;
473 SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
475 char* working_dir = 0;
477 if (pid) { return 0; }
479 pid = new PROCESS_INFORMATION;
480 memset(pid, 0, sizeof(PROCESS_INFORMATION));
482 create_pipe(stdinP, true);
483 create_pipe(stdoutP, false);
485 if (stderr_mode == 2) {
486 /* merge stout & stderr */
487 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
488 } else if (stderr_mode == 1) {
489 //TODO read/flush this pipe or close it...
490 create_pipe(stderrP, false);
492 //TODO: keep stderr of this process mode.
495 bool success = false;
496 STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
497 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
498 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
500 STARTF_USESTDHANDLES,
502 stdinP[0], stdoutP[1], stderrP[1]
505 success = CreateProcess(0, w_args,
506 0, 0, /* bInheritHandles = */ TRUE,
507 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
512 if (stdinP[0] != INVALID_HANDLE_VALUE) {
513 CloseHandle(stdinP[0]);
514 stdinP[0] = INVALID_HANDLE_VALUE;
516 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
517 CloseHandle(stdoutP[1]);
518 stdoutP[1] = INVALID_HANDLE_VALUE;
520 if (stderrP[1] != INVALID_HANDLE_VALUE) {
521 CloseHandle(stderrP[1]);
522 stderrP[1] = INVALID_HANDLE_VALUE;
526 CloseHandle(pid->hThread);
527 CloseHandle(pid->hProcess);
528 destroy_pipe(stdinP);
529 destroy_pipe(stdoutP);
530 destroy_pipe(stderrP);
536 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
548 SystemExec::output_interposer()
552 #if 0 // untested code to set up nonblocking
554 ioctlsocket(stdoutP[0], FIONBIO, &l);
557 #if 0 // for non-blocking pipes..
558 DWORD bytesAvail = 0;
559 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
560 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
562 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
563 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) {
564 DWORD err = GetLastError();
565 if (err == ERROR_IO_PENDING) continue;
568 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
570 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
572 Terminated();/* EMIT SIGNAL */
577 SystemExec::close_stdin()
579 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
580 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
582 destroy_pipe(stdinP);
586 SystemExec::write_to_stdin(std::string d, size_t len)
591 ::pthread_mutex_lock(&write_lock);
599 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
600 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
604 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
610 ::pthread_mutex_unlock(&write_lock);
615 /* end windows process */
617 /* UNIX/POSIX process */
619 extern char **environ;
621 SystemExec::make_envp() {
623 envp = (char **) calloc(1, sizeof(char*));
624 /* copy current environment */
625 for (i=0;environ[i];++i) {
626 envp[i] = strdup(environ[i]);
627 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
633 SystemExec::make_argp(std::string args) {
638 char *carg = strdup(args.c_str());
640 argp = (char **) malloc((argn + 1) * sizeof(char *));
641 if (argp == (char **) 0) {
646 argp[0] = strdup(cmd.c_str());
648 /* TODO: quotations and escapes
649 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
651 * It's actually not needed. All relevant invocations specify 'argp' directly.
652 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
653 * nor arguments with white-space.
655 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
658 argp[argn++] = strdup(cp1);
660 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
664 argp[argn++] = strdup(cp1);
665 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
667 argp[argn] = (char *) 0;
674 SystemExec::terminate ()
676 ::pthread_mutex_lock(&write_lock);
678 /* close stdin in an attempt to get the child to exit cleanly.
689 /* if pid is non-zero, the child task is still executing (i.e. it did
690 * not exit in response to stdin being closed). try to kill it.
694 ::kill(pid, SIGTERM);
700 /* if pid is non-zero, the child task is STILL executing after being
701 * sent SIGTERM. Act tough ... send SIGKILL
705 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
706 ::kill(pid, SIGKILL);
710 if (thread_active) pthread_join(thread_id_tt, NULL);
711 thread_active = false;
713 ::pthread_mutex_unlock(&write_lock);
717 SystemExec::wait (int options)
722 if (pid==0) return -1;
724 ret = waitpid (pid, &status, options);
727 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
732 if (errno == ECHILD) {
733 /* no currently running children, reset pid */
736 } /* else the process is still running */
742 SystemExec::is_running ()
745 if (pid==0) return false;
746 if (::waitpid(pid, &status, WNOHANG)==0) return true;
751 SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
754 return 0; // mmh what to return here?
758 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
759 /* Something unexpected went wrong creating a pipe. */
777 /* check if execve was successful. */
781 ssize_t n = ::read(pok[0], &buf, 1 );
783 /* child process returned from execve */
792 } else if ( n==-1 ) {
793 if ( errno==EAGAIN || errno==EINTR )
799 /* child started successfully */
803 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
811 return 0; /* all systems go - return to main */
815 /* child process - exec external process */
817 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
820 if (pin[0] != STDIN_FILENO) {
821 ::dup2(pin[0], STDIN_FILENO);
825 if (pout[1] != STDOUT_FILENO) {
826 ::dup2(pout[1], STDOUT_FILENO);
829 if (stderr_mode == 2) {
830 /* merge STDERR into output */
831 if (pout[1] != STDERR_FILENO) {
832 ::dup2(pout[1], STDERR_FILENO);
834 } else if (stderr_mode == 1) {
836 ::close(STDERR_FILENO);
841 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
850 sigset(SIGPIPE, SIG_DFL);
852 signal(SIGPIPE, SIG_DFL);
854 if (!vfork_exec_wrapper) {
855 error << _("Cannot start external process, no vfork wrapper") << endmsg;
859 int good_fds[2] = { pok[1], -1 };
860 close_allv(good_fds);
862 ::execve(argp[0], argp, envp);
863 /* if we reach here something went wrong.. */
865 (void) ::write(pok[1], &buf, 1 );
871 /* XXX this should be done before vfork()
872 * calling malloc here only increases the time vfork() blocks
875 for (int i=0;argp[i];++i) { argn++; }
876 char **argx = (char **) malloc((argn + 10) * sizeof(char *));
877 argx[0] = strdup(vfork_exec_wrapper); // XXX
879 #define FDARG(NUM, FDN) \
880 argx[NUM] = (char*) calloc(6, sizeof(char)); snprintf(argx[NUM], 6, "%d", FDN);
888 FDARG(7, stderr_mode)
891 for (int i=0;argp[i];++i) {
896 ::execve(argx[0], argx, envp);
898 /* if we reach here something went wrong.. */
900 (void) ::write(pok[1], &buf, 1 );
908 SystemExec::output_interposer()
915 ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
917 for (;fcntl(rfd, F_GETFL)!=-1;) {
918 r = read(rfd, buf, sizeof(buf));
919 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
926 int rv = select(1, &rfds, NULL, NULL, &tv);
936 std::string rv = std::string(buf,r); // TODO: check allocation strategy
937 ReadStdout(rv, r);/* EMIT SIGNAL */
939 Terminated();/* EMIT SIGNAL */
944 SystemExec::close_stdin()
946 if (pin[1]<0) return;
954 SystemExec::write_to_stdin(std::string d, size_t len)
959 ::pthread_mutex_lock(&write_lock);
968 r=::write(pin[1], data+c, len-c);
969 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
973 if ((size_t) r != (len-c)) {
974 ::pthread_mutex_unlock(&write_lock);
982 ::pthread_mutex_unlock(&write_lock);
986 #endif // end UNIX process