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;
174 #elif !defined NO_VFORK
179 SystemExec::SystemExec (std::string c, std::string a)
189 SystemExec::SystemExec (std::string c, char **a)
194 #ifdef PLATFORM_WINDOWS
200 SystemExec::SystemExec (std::string command, const std::map<char, std::string> subs)
203 make_argp_escaped(command, subs);
205 #ifdef PLATFORM_WINDOWS
206 if (argp[0] && strlen (argp[0]) > 0) {
207 std::string wa = argp[0];
208 // only add quotes to command if required..
209 if (argp[0][0] != '"'
210 && argp[0][strlen(argp[0])-1] != '"'
211 && strchr(argp[0], ' ')) {
216 // ...but always quote all args
217 for (int i = 1; argp[i]; ++i) {
218 std::string tmp (argp[i]);
219 while (tmp.find("\"") != std::string::npos)
220 tmp.replace(tmp.find("\""), 1, "\\\"");
225 w_args = strdup(wa.c_str());
228 if (find_file (Searchpath (Glib::getenv ("PATH")), argp[0], cmd)) {
229 // argp[0] exists in $PATH` - set it to the actual path where it was found
231 argp[0] = strdup(cmd.c_str ());
233 // else argp[0] not found in path - leave it as-is, it might be an absolute path
235 // Glib::find_program_in_path () is only available in Glib >= 2.28
236 // cmd = Glib::find_program_in_path (argp[0]);
242 SystemExec::format_key_value_parameter (std::string key, std::string value)
244 size_t start_pos = 0;
245 std::string v1 = value;
246 while((start_pos = v1.find_first_not_of(
247 "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789(),.\"'",
248 start_pos)) != std::string::npos)
250 v1.replace(start_pos, 1, "_");
255 while((start_pos = v1.find("\"", start_pos)) != std::string::npos) {
256 v1.replace(start_pos, 1, "\\\"");
260 size_t len = key.length() + v1.length() + 4;
261 char *mds = (char*) calloc(len, sizeof(char));
262 #ifdef PLATFORM_WINDOWS
263 /* SystemExec::make_wargs() adds quotes around the complete argument
264 * windows uses CreateProcess() with a parameter string
265 * (and not an array list of separate arguments)
267 snprintf(mds, len, "%s=%s", key.c_str(), v1.c_str());
269 snprintf(mds, len, "%s=\"%s\"", key.c_str(), v1.c_str());
275 SystemExec::make_argp_escaped(std::string command, const std::map<char, std::string> subs)
281 std::string arg = "";
283 argp = (char **) malloc(sizeof(char *));
285 for (i = 0; i <= command.length(); i++) { // include terminating '\0'
286 char c = command.c_str()[i];
291 // still in quotes - just copy
296 c = command.c_str()[++i];
297 if (c == '%' || c == '\0') {
298 // "%%", "%" at end-of-string => "%"
301 // search subs for string to substitute for char
302 std::map<char, std::string>::const_iterator s = subs.find(c);
303 if (s != subs.end()) {
304 // found substitution
307 // not a valid substitution, just copy
314 c = command.c_str()[++i];
317 case '"' : arg += c; break; // "\\", "\" at end-of-string => "\"
319 case '\\': arg += '\\'; break;
320 default : arg += '\\'; arg += c; break;
329 if (arg.length() > 0) {
330 // if there wasn't already a space or tab, start a new parameter
331 argp = (char **) realloc(argp, (n + 2) * sizeof(char *));
332 argp[n++] = strdup (arg.c_str());
344 SystemExec::~SystemExec ()
348 for (int i=0;envp[i];++i) {
354 for (int i=0;argp[i];++i) {
359 #ifdef PLATFORM_WINDOWS
360 if (w_args) free(w_args);
361 #elif !defined NO_VFORK
363 /* argx[0 .. 8] are fixed parameters to vfork-exec-wrapper */
364 for (int i = 0; i < 9; ++i) {
370 pthread_mutex_destroy(&write_lock);
374 interposer_thread (void *arg) {
375 SystemExec *sex = static_cast<SystemExec *>(arg);
376 sex->output_interposer();
382 SystemExec::to_s () const
384 #ifdef PLATFORM_WINDOWS
385 return string (w_args ? w_args : "");
389 for (int i = 0; argp[i]; ++i) {
390 out << argp[i] << " ";
398 SystemExec::write_to_stdin (std::string const& d, size_t len)
400 const char *data = d.c_str();
404 return write_to_stdin ((const void*)data, len);
407 #ifdef PLATFORM_WINDOWS /* Windows Process */
409 /* HELPER FUNCTIONS */
411 static void create_pipe (HANDLE *pipe, bool in) {
412 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
415 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
416 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
418 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
419 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
421 CloseHandle(tmpHandle);
424 static void destroy_pipe (HANDLE pipe[2]) {
425 if (pipe[0] != INVALID_HANDLE_VALUE) {
426 CloseHandle(pipe[0]);
427 pipe[0] = INVALID_HANDLE_VALUE;
429 if (pipe[1] != INVALID_HANDLE_VALUE) {
430 CloseHandle(pipe[1]);
431 pipe[1] = INVALID_HANDLE_VALUE;
435 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
437 DWORD currentProcId = 0;
438 GetWindowThreadProcessId(hwnd, ¤tProcId);
439 if (currentProcId == (DWORD)procId)
440 PostMessage(hwnd, WM_CLOSE, 0, 0);
447 SystemExec::make_envp() {
448 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
452 SystemExec::make_wargs(char **a) {
453 std::string wa = cmd;
454 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
455 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
457 while (tmp && *tmp) {
460 if (strlen(*tmp) > 0 && (*tmp)[strlen(*tmp) - 1] == '\\') {
466 w_args = strdup(wa.c_str());
470 SystemExec::make_argp(std::string args) {
471 std::string wa = cmd;
472 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
473 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
476 w_args = strdup(wa.c_str());
480 SystemExec::terminate ()
482 ::pthread_mutex_lock(&write_lock);
488 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
489 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
492 TerminateProcess(pid->hProcess, 0xf291);
494 CloseHandle(pid->hThread);
495 CloseHandle(pid->hProcess);
496 destroy_pipe(stdinP);
497 destroy_pipe(stdoutP);
498 destroy_pipe(stderrP);
502 ::pthread_mutex_unlock(&write_lock);
506 SystemExec::wait (int options)
508 while (is_running()) {
509 WaitForSingleObject(pid->hProcess, 40);
515 SystemExec::is_running ()
517 if (!pid) return false;
519 if (GetExitCodeProcess(pid->hProcess, &exit_code)) {
520 if (exit_code == STILL_ACTIVE) return true;
526 SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
528 char* working_dir = 0;
530 if (pid) { return 0; }
532 pid = new PROCESS_INFORMATION;
533 memset(pid, 0, sizeof(PROCESS_INFORMATION));
535 create_pipe(stdinP, true);
536 create_pipe(stdoutP, false);
538 if (stderr_mode == 2) {
539 /* merge stout & stderr */
540 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
541 } else if (stderr_mode == 1) {
542 //TODO read/flush this pipe or close it...
543 create_pipe(stderrP, false);
545 //TODO: keep stderr of this process mode.
548 bool success = false;
549 STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
550 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
551 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
553 STARTF_USESTDHANDLES,
555 stdinP[0], stdoutP[1], stderrP[1]
558 success = CreateProcess(0, w_args,
559 0, 0, /* bInheritHandles = */ TRUE,
560 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
565 if (stdinP[0] != INVALID_HANDLE_VALUE) {
566 CloseHandle(stdinP[0]);
567 stdinP[0] = INVALID_HANDLE_VALUE;
569 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
570 CloseHandle(stdoutP[1]);
571 stdoutP[1] = INVALID_HANDLE_VALUE;
573 if (stderrP[1] != INVALID_HANDLE_VALUE) {
574 CloseHandle(stderrP[1]);
575 stderrP[1] = INVALID_HANDLE_VALUE;
579 CloseHandle(pid->hThread);
580 CloseHandle(pid->hProcess);
581 destroy_pipe(stdinP);
582 destroy_pipe(stdoutP);
583 destroy_pipe(stderrP);
589 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
601 SystemExec::output_interposer()
605 #if 0 // untested code to set up nonblocking
607 ioctlsocket(stdoutP[0], FIONBIO, &l);
610 #if 0 // for non-blocking pipes..
611 DWORD bytesAvail = 0;
612 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
613 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
615 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
616 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) {
617 DWORD err = GetLastError();
618 if (err == ERROR_IO_PENDING) continue;
621 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
623 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
625 Terminated();/* EMIT SIGNAL */
630 SystemExec::close_stdin()
632 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
633 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
635 destroy_pipe(stdinP);
639 SystemExec::write_to_stdin(const void* data, size_t bytes)
643 ::pthread_mutex_lock(&write_lock);
647 if (!WriteFile(stdinP[1], &((const char*)data)[c], bytes - c, &r, NULL)) {
648 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
652 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
658 ::pthread_mutex_unlock(&write_lock);
663 /* end windows process */
665 /* UNIX/POSIX process */
667 extern char **environ;
669 SystemExec::make_envp() {
671 envp = (char **) calloc(1, sizeof(char*));
672 /* copy current environment */
673 for (i=0;environ[i];++i) {
674 envp[i] = strdup(environ[i]);
675 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
681 SystemExec::make_argp(std::string args) {
686 char *carg = strdup(args.c_str());
688 argp = (char **) malloc((argn + 1) * sizeof(char *));
689 if (argp == (char **) 0) {
694 argp[0] = strdup(cmd.c_str());
696 /* TODO: quotations and escapes
697 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
699 * It's actually not needed. All relevant invocations specify 'argp' directly.
700 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
701 * nor arguments with white-space.
703 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
706 argp[argn++] = strdup(cp1);
708 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
712 argp[argn++] = strdup(cp1);
713 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
715 argp[argn] = (char *) 0;
722 SystemExec::terminate ()
724 ::pthread_mutex_lock(&write_lock);
726 /* close stdin in an attempt to get the child to exit cleanly.
737 /* if pid is non-zero, the child task is still executing (i.e. it did
738 * not exit in response to stdin being closed). try to kill it.
742 ::kill(pid, SIGTERM);
748 /* if pid is non-zero, the child task is STILL executing after being
749 * sent SIGTERM. Act tough ... send SIGKILL
753 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
754 ::kill(pid, SIGKILL);
758 if (thread_active) pthread_join(thread_id_tt, NULL);
759 thread_active = false;
761 ::pthread_mutex_unlock(&write_lock);
765 SystemExec::wait (int options)
770 if (pid==0) return -1;
772 ret = waitpid (pid, &status, options);
775 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
780 if (errno == ECHILD) {
781 /* no currently running children, reset pid */
784 } /* else the process is still running */
790 SystemExec::is_running ()
793 if (pid==0) return false;
794 if (::waitpid(pid, &status, WNOHANG)==0) return true;
799 SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
802 return 0; // mmh what to return here?
806 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
807 /* Something unexpected went wrong creating a pipe. */
825 /* check if execve was successful. */
829 ssize_t n = ::read(pok[0], &buf, 1 );
831 /* child process returned from execve */
840 } else if ( n==-1 ) {
841 if ( errno==EAGAIN || errno==EINTR )
847 /* child started successfully */
851 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
859 return 0; /* all systems go - return to main */
863 /* child process - exec external process */
865 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
868 if (pin[0] != STDIN_FILENO) {
869 ::dup2(pin[0], STDIN_FILENO);
873 if (pout[1] != STDOUT_FILENO) {
874 ::dup2(pout[1], STDOUT_FILENO);
877 if (stderr_mode == 2) {
878 /* merge STDERR into output */
879 if (pout[1] != STDERR_FILENO) {
880 ::dup2(pout[1], STDERR_FILENO);
882 } else if (stderr_mode == 1) {
884 ::close(STDERR_FILENO);
889 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
898 sigset(SIGPIPE, SIG_DFL);
900 signal(SIGPIPE, SIG_DFL);
902 if (!vfork_exec_wrapper) {
903 error << _("Cannot start external process, no vfork wrapper") << endmsg;
907 int good_fds[2] = { pok[1], -1 };
908 close_allv(good_fds);
910 ::execve(argp[0], argp, envp);
911 /* if we reach here something went wrong.. */
913 (void) ::write(pok[1], &buf, 1 );
919 /* XXX this should be done before vfork()
920 * calling malloc here only increases the time vfork() blocks
923 for (int i=0;argp[i];++i) { argn++; }
925 argx = (char **) malloc((argn + 10) * sizeof(char *));
926 argx[0] = strdup(vfork_exec_wrapper);
928 #define FDARG(NUM, FDN) \
929 argx[NUM] = (char*) calloc(6, sizeof(char)); snprintf(argx[NUM], 6, "%d", FDN);
937 FDARG(7, stderr_mode)
940 for (int i=0;argp[i];++i) {
945 ::execve(argx[0], argx, envp);
947 /* if we reach here something went wrong.. */
949 (void) ::write(pok[1], &buf, 1 );
957 SystemExec::output_interposer()
964 ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
966 for (;fcntl(rfd, F_GETFL)!=-1;) {
967 r = read(rfd, buf, sizeof(buf));
968 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
975 int rv = select(1, &rfds, NULL, NULL, &tv);
985 std::string rv = std::string(buf,r); // TODO: check allocation strategy
986 ReadStdout(rv, r);/* EMIT SIGNAL */
988 Terminated();/* EMIT SIGNAL */
993 SystemExec::close_stdin()
995 if (pin[1]<0) return;
1003 SystemExec::write_to_stdin(const void* data, size_t bytes)
1007 ::pthread_mutex_lock(&write_lock);
1012 r = ::write(pin[1], &((const char*)data)[c], bytes - c);
1013 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
1017 if ((size_t) r != (bytes-c)) {
1018 ::pthread_mutex_unlock(&write_lock);
1026 ::pthread_mutex_unlock(&write_lock);
1030 #endif // end UNIX process