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>
48 #include "pbd/file_utils.h"
49 #include "pbd/search_path.h"
50 #include "pbd/system_exec.h"
55 static void * interposer_thread (void *arg);
57 #ifndef PLATFORM_WINDOWS /* POSIX Process only */
58 static void close_fd (int& fd) { if (fd >= 0) ::close (fd); fd = -1; }
61 #if (!defined PLATFORM_WINDOWS && defined NO_VFORK)
63 * This function was part of libasyncns.
65 * Copyright 2005-2008 Lennart Poettering
67 static int close_allv(const int except_fds[]) {
77 if ((d = opendir("/proc/self/fd"))) {
80 while ((de = readdir(d))) {
86 if (de->d_name[0] == '.')
90 l = strtol(de->d_name, &e, 10);
91 if (errno != 0 || !e || *e) {
112 for (i = 0; except_fds[i] >= 0; i++)
113 if (except_fds[i] == fd) {
137 if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
140 for (fd = 0; fd < (int) rl.rlim_max; fd++) {
146 for (i = 0; except_fds[i] >= 0; i++)
147 if (except_fds[i] == fd)
150 if (close(fd) < 0 && errno != EBADF)
156 #endif /* not on windows, nor vfork */
161 pthread_mutex_init (&write_lock, NULL);
162 thread_active = false;
167 #ifdef PLATFORM_WINDOWS
168 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
169 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
170 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
172 #elif !defined NO_VFORK
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::format_key_value_parameter (std::string key, std::string value)
242 size_t start_pos = 0;
243 std::string v1 = value;
244 while((start_pos = v1.find_first_not_of(
245 "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789(),.\"'",
246 start_pos)) != std::string::npos)
248 v1.replace(start_pos, 1, "_");
253 while((start_pos = v1.find("\"", start_pos)) != std::string::npos) {
254 v1.replace(start_pos, 1, "\\\"");
258 size_t len = key.length() + v1.length() + 4;
259 char *mds = (char*) calloc(len, sizeof(char));
260 #ifdef PLATFORM_WINDOWS
261 /* SystemExec::make_wargs() adds quotes around the complete argument
262 * windows uses CreateProcess() with a parameter string
263 * (and not an array list of separate arguments)
265 snprintf(mds, len, "%s=%s", key.c_str(), v1.c_str());
267 snprintf(mds, len, "%s=\"%s\"", key.c_str(), v1.c_str());
273 SystemExec::make_argp_escaped (std::string command, const std::map<char, std::string> subs)
279 std::string arg = "";
281 argp = (char**) malloc (sizeof(char*));
283 for (i = 0; i <= command.length(); i++) { // include terminating '\0'
284 char c = command.c_str()[i];
289 // still in quotes - just copy
294 c = command.c_str()[++i];
295 if (c == '%' || c == '\0') {
296 // "%%", "%" at end-of-string => "%"
299 // search subs for string to substitute for char
300 std::map<char, std::string>::const_iterator s = subs.find(c);
301 if (s != subs.end()) {
302 // found substitution
305 // not a valid substitution, just copy
312 c = command.c_str()[++i];
315 case '"' : arg += c; break; // "\\", "\" at end-of-string => "\"
317 case '\\': arg += '\\'; break;
318 default : arg += '\\'; arg += c; break;
327 if (arg.length() > 0) {
328 // if there wasn't already a space or tab, start a new parameter
329 argp = (char **) realloc(argp, (n + 2) * sizeof(char *));
330 argp[n++] = strdup (arg.c_str());
342 SystemExec::~SystemExec ()
346 for (int i = 0; envp[i]; ++i) {
352 for (int i = 0; argp[i]; ++i) {
357 #ifdef PLATFORM_WINDOWS
358 if (w_args) free(w_args);
359 #elif !defined NO_VFORK
361 /* argx[0 .. 8] are fixed parameters to vfork-exec-wrapper */
362 for (int i = 0; i < 9; ++i) {
368 pthread_mutex_destroy(&write_lock);
372 interposer_thread (void *arg) {
373 SystemExec *sex = static_cast<SystemExec *>(arg);
374 sex->output_interposer();
380 SystemExec::to_s () const
382 #ifdef PLATFORM_WINDOWS
383 return string (w_args ? w_args : "");
387 for (int i = 0; argp[i]; ++i) {
388 out << argp[i] << " ";
396 SystemExec::write_to_stdin (std::string const& d, size_t len)
398 const char *data = d.c_str();
402 return write_to_stdin ((const void*)data, len);
405 #ifdef PLATFORM_WINDOWS /* Windows Process */
407 /* HELPER FUNCTIONS */
410 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);
425 destroy_pipe (HANDLE pipe[2])
427 if (pipe[0] != INVALID_HANDLE_VALUE) {
428 CloseHandle(pipe[0]);
429 pipe[0] = INVALID_HANDLE_VALUE;
431 if (pipe[1] != INVALID_HANDLE_VALUE) {
432 CloseHandle(pipe[1]);
433 pipe[1] = INVALID_HANDLE_VALUE;
438 CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
440 DWORD currentProcId = 0;
441 GetWindowThreadProcessId(hwnd, ¤tProcId);
442 if (currentProcId == (DWORD)procId)
443 PostMessage(hwnd, WM_CLOSE, 0, 0);
450 SystemExec::make_envp()
452 ; /* environemt is copied over with CreateProcess(...,env=0 ,..) */
456 SystemExec::make_wargs (char** a)
458 std::string wa = cmd;
459 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
460 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
462 while (tmp && *tmp) {
465 if (strlen(*tmp) > 0 && (*tmp)[strlen(*tmp) - 1] == '\\') {
471 w_args = strdup(wa.c_str());
475 SystemExec::make_argp (std::string args)
477 std::string wa = cmd;
478 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
479 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
482 w_args = strdup(wa.c_str());
486 SystemExec::terminate ()
488 ::pthread_mutex_lock(&write_lock);
494 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
495 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
498 TerminateProcess(pid->hProcess, 0xf291);
500 CloseHandle(pid->hThread);
501 CloseHandle(pid->hProcess);
502 destroy_pipe(stdinP);
503 destroy_pipe(stdoutP);
504 destroy_pipe(stderrP);
508 ::pthread_mutex_unlock(&write_lock);
512 SystemExec::wait (int options)
514 while (is_running()) {
515 WaitForSingleObject(pid->hProcess, 40);
521 SystemExec::is_running ()
523 if (!pid) return false;
525 if (GetExitCodeProcess(pid->hProcess, &exit_code)) {
526 if (exit_code == STILL_ACTIVE) return true;
532 SystemExec::start (StdErrMode stderr_mode, const char * /*vfork_exec_wrapper*/)
534 char* working_dir = 0;
536 if (pid) { return 0; }
538 pid = new PROCESS_INFORMATION;
539 memset(pid, 0, sizeof(PROCESS_INFORMATION));
541 create_pipe(stdinP, true);
542 create_pipe(stdoutP, false);
544 if (stderr_mode == MergeWithStdin) {
545 /* merge stout & stderr */
546 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
547 } else if (stderr_mode == IgnoreAndClose) {
548 //TODO read/flush this pipe or close it...
549 create_pipe(stderrP, false);
551 //TODO: keep stderr of this process mode.
554 bool success = false;
555 STARTUPINFOA startupInfo = { sizeof(STARTUPINFO), 0, 0, 0,
556 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
557 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
559 STARTF_USESTDHANDLES,
561 stdinP[0], stdoutP[1], stderrP[1]
564 success = CreateProcess(0, w_args,
565 0, 0, /* bInheritHandles = */ TRUE,
566 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
571 if (stdinP[0] != INVALID_HANDLE_VALUE) {
572 CloseHandle(stdinP[0]);
573 stdinP[0] = INVALID_HANDLE_VALUE;
575 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
576 CloseHandle(stdoutP[1]);
577 stdoutP[1] = INVALID_HANDLE_VALUE;
579 if (stderrP[1] != INVALID_HANDLE_VALUE) {
580 CloseHandle(stderrP[1]);
581 stderrP[1] = INVALID_HANDLE_VALUE;
585 CloseHandle(pid->hThread);
586 CloseHandle(pid->hProcess);
587 destroy_pipe(stdinP);
588 destroy_pipe(stdoutP);
589 destroy_pipe(stderrP);
595 int rv = pthread_create (&thread_id_tt, NULL, interposer_thread, this);
607 SystemExec::output_interposer()
611 #if 0 // untested code to set up nonblocking
613 ioctlsocket(stdoutP[0], FIONBIO, &l);
616 #if 0 // for non-blocking pipes..
617 DWORD bytesAvail = 0;
618 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
619 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
621 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
622 if (!ReadFile(stdoutP[0], data, BUFSIZ - 1, &bytesRead, 0)) {
623 DWORD err = GetLastError();
624 if (err == ERROR_IO_PENDING) continue;
627 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
629 ReadStdout(data, bytesRead); /* EMIT SIGNAL */
631 Terminated(); /* EMIT SIGNAL */
636 SystemExec::close_stdin()
638 if (stdinP[0] != INVALID_HANDLE_VALUE) FlushFileBuffers (stdinP[0]);
639 if (stdinP[1] != INVALID_HANDLE_VALUE) FlushFileBuffers (stdinP[1]);
641 destroy_pipe (stdinP);
645 SystemExec::write_to_stdin (const void* data, size_t bytes)
649 ::pthread_mutex_lock (&write_lock);
653 if (!WriteFile (stdinP[1], &((const char*)data)[c], bytes - c, &r, NULL)) {
654 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
658 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
664 ::pthread_mutex_unlock(&write_lock);
669 /* end windows process */
671 /* UNIX/POSIX process */
673 extern char **environ;
676 SystemExec::make_envp()
679 envp = (char **) calloc(1, sizeof(char*));
680 /* copy current environment */
681 for (i = 0; environ[i]; ++i) {
682 envp[i] = strdup(environ[i]);
683 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
689 SystemExec::make_argp(std::string args)
695 char *carg = strdup(args.c_str());
697 argp = (char **) malloc((argn + 1) * sizeof(char *));
698 if (argp == (char **) 0) {
703 argp[0] = strdup(cmd.c_str());
705 /* TODO: quotations and escapes
706 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
708 * It's actually not needed. All relevant invocations specify 'argp' directly.
709 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
710 * nor arguments with white-space.
712 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
715 argp[argn++] = strdup(cp1);
717 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
721 argp[argn++] = strdup(cp1);
722 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
724 argp[argn] = (char *) 0;
729 SystemExec::terminate ()
731 ::pthread_mutex_lock(&write_lock);
733 /* close stdin in an attempt to get the child to exit cleanly.
744 /* if pid is non-zero, the child task is still executing (i.e. it did
745 * not exit in response to stdin being closed). try to kill it.
749 ::kill(pid, SIGTERM);
755 /* if pid is non-zero, the child task is STILL executing after being
756 * sent SIGTERM. Act tough ... send SIGKILL
760 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
761 ::kill(pid, SIGKILL);
765 if (thread_active) pthread_join(thread_id_tt, NULL);
766 thread_active = false;
768 ::pthread_mutex_unlock(&write_lock);
772 SystemExec::wait (int options)
777 if (pid == 0) return -1;
779 ret = waitpid (pid, &status, options);
782 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
787 if (errno == ECHILD) {
788 /* no currently running children, reset pid */
791 } /* else the process is still running */
797 SystemExec::is_running ()
803 if (::waitpid (pid, &status, WNOHANG)==0) {
810 SystemExec::start (StdErrMode stderr_mode, const char *vfork_exec_wrapper)
818 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
819 /* Something unexpected went wrong creating a pipe. */
837 /* check if execve was successful. */
841 ssize_t n = ::read (pok[0], &buf, 1);
843 /* child process returned from execve */
852 } else if (n == -1) {
853 if (errno==EAGAIN || errno==EINTR) {
861 /* child started successfully */
866 int rv = pthread_create (&thread_id_tt, NULL, interposer_thread, this);
874 return 0; /* all systems go - return to main */
878 /* child process - exec external process */
880 ::fcntl (pok[1], F_SETFD, FD_CLOEXEC);
883 if (pin[0] != STDIN_FILENO) {
884 ::dup2 (pin[0], STDIN_FILENO);
888 if (pout[1] != STDOUT_FILENO) {
889 ::dup2 (pout[1], STDOUT_FILENO);
892 if (stderr_mode == MergeWithStdin) {
893 /* merge STDERR into output */
894 if (pout[1] != STDERR_FILENO) {
895 ::dup2(pout[1], STDERR_FILENO);
897 } else if (stderr_mode == IgnoreAndClose) {
899 ::close(STDERR_FILENO);
900 } else { /* stderr_mode == ShareWithParent */
902 #if defined __APPLE__&& defined ASL_LOG_DESCRIPTOR_WRITE
903 ::close(STDERR_FILENO);
904 stderr_mode = IgnoreAndClose; // for vfork
908 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
917 sigset (SIGPIPE, SIG_DFL);
919 signal (SIGPIPE, SIG_DFL);
921 if (!vfork_exec_wrapper) {
922 error << _("Cannot start external process, no vfork wrapper") << endmsg;
926 int good_fds[2] = { pok[1], -1 };
927 close_allv(good_fds);
929 ::execve(argp[0], argp, envp);
931 #else /* ! NO_VFORK */
933 /* XXX this should be done before vfork()
934 * calling malloc here only increases the time vfork() blocks
937 for (int i = 0; argp[i]; ++i) { argn++; }
939 argx = (char **) malloc ((argn + 10) * sizeof(char*));
940 argx[0] = strdup (vfork_exec_wrapper);
942 #define FDARG(NUM, FDN) \
943 argx[NUM] = (char*) calloc(6, sizeof(char)); snprintf(argx[NUM], 6, "%d", FDN);
951 FDARG (7, stderr_mode)
954 for (int i = 0; argp[i]; ++i) {
959 ::execve (argx[0], argx, envp);
962 /* if we reach here something went wrong.. */
964 (void) ::write (pok[1], &buf, 1);
971 SystemExec::output_interposer ()
978 ioctl (rfd, FIONBIO, &l); // set non-blocking I/O
980 for (;fcntl (rfd, F_GETFL) != -1;) {
981 r = read (rfd, buf, BUFSIZ - 1);
982 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
989 int rv = select (1, &rfds, NULL, NULL, &tv);
999 std::string rv = std::string (buf, r);
1000 ReadStdout (rv, r); /* EMIT SIGNAL */
1002 Terminated (); /* EMIT SIGNAL */
1007 SystemExec::close_stdin()
1019 SystemExec::write_to_stdin (const void* data, size_t bytes)
1023 ::pthread_mutex_lock (&write_lock);
1028 r = ::write (pin[1], &((const char*)data)[c], bytes - c);
1029 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
1033 if ((size_t) r != (bytes-c)) {
1034 ::pthread_mutex_unlock(&write_lock);
1042 ::pthread_mutex_unlock(&write_lock);
1046 #endif // end UNIX process