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, "_");
252 #ifdef PLATFORM_WINDOWS
253 /* SystemExec::make_wargs() adds quotes around the complete argument
254 * windows uses CreateProcess() with a parameter string
255 * (and not an array list of separate arguments like Unix)
256 * so quotes need to be escaped.
259 while((start_pos = v1.find("\"", start_pos)) != std::string::npos) {
260 v1.replace(start_pos, 1, "\\\"");
265 size_t len = key.length() + v1.length() + 2;
266 char *mds = (char*) calloc(len, sizeof(char));
267 snprintf(mds, len, "%s=%s", key.c_str(), v1.c_str());
272 SystemExec::make_argp_escaped (std::string command, const std::map<char, std::string> subs)
278 std::string arg = "";
280 argp = (char**) malloc (sizeof(char*));
282 for (i = 0; i <= command.length(); i++) { // include terminating '\0'
283 char c = command.c_str()[i];
288 // still in quotes - just copy
293 c = command.c_str()[++i];
294 if (c == '%' || c == '\0') {
295 // "%%", "%" at end-of-string => "%"
298 // search subs for string to substitute for char
299 std::map<char, std::string>::const_iterator s = subs.find(c);
300 if (s != subs.end()) {
301 // found substitution
304 // not a valid substitution, just copy
311 c = command.c_str()[++i];
314 case '"' : arg += c; break; // "\\", "\" at end-of-string => "\"
316 case '\\': arg += '\\'; break;
317 default : arg += '\\'; arg += c; break;
326 if (arg.length() > 0) {
327 // if there wasn't already a space or tab, start a new parameter
328 argp = (char **) realloc(argp, (n + 2) * sizeof(char *));
329 argp[n++] = strdup (arg.c_str());
341 SystemExec::~SystemExec ()
345 for (int i = 0; envp[i]; ++i) {
351 for (int i = 0; argp[i]; ++i) {
356 #ifdef PLATFORM_WINDOWS
357 if (w_args) free(w_args);
358 #elif !defined NO_VFORK
360 /* argx[0 .. 8] are fixed parameters to vfork-exec-wrapper */
361 for (int i = 0; i < 9; ++i) {
367 pthread_mutex_destroy(&write_lock);
371 interposer_thread (void *arg) {
372 SystemExec *sex = static_cast<SystemExec *>(arg);
373 sex->output_interposer();
379 SystemExec::to_s () const
381 #ifdef PLATFORM_WINDOWS
382 return string (w_args ? w_args : "");
386 for (int i = 0; argp[i]; ++i) {
387 out << argp[i] << " ";
395 SystemExec::write_to_stdin (std::string const& d, size_t len)
397 const char *data = d.c_str();
401 return write_to_stdin ((const void*)data, len);
404 #ifdef PLATFORM_WINDOWS /* Windows Process */
406 /* HELPER FUNCTIONS */
409 create_pipe (HANDLE *pipe, bool in)
411 SECURITY_ATTRIBUTES secAtt = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
414 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
415 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
417 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
418 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
420 CloseHandle(tmpHandle);
424 destroy_pipe (HANDLE pipe[2])
426 if (pipe[0] != INVALID_HANDLE_VALUE) {
427 CloseHandle(pipe[0]);
428 pipe[0] = INVALID_HANDLE_VALUE;
430 if (pipe[1] != INVALID_HANDLE_VALUE) {
431 CloseHandle(pipe[1]);
432 pipe[1] = INVALID_HANDLE_VALUE;
437 CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
439 DWORD currentProcId = 0;
440 GetWindowThreadProcessId(hwnd, ¤tProcId);
441 if (currentProcId == (DWORD)procId)
442 PostMessage(hwnd, WM_CLOSE, 0, 0);
449 SystemExec::make_envp()
451 ; /* environemt is copied over with CreateProcess(...,env=0 ,..) */
455 SystemExec::make_wargs (char** a)
457 std::string wa = cmd;
458 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
459 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
461 while (tmp && *tmp) {
464 if (strlen(*tmp) > 0 && (*tmp)[strlen(*tmp) - 1] == '\\') {
470 w_args = strdup(wa.c_str());
474 SystemExec::make_argp (std::string args)
476 std::string wa = cmd;
477 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
478 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
481 w_args = strdup(wa.c_str());
485 SystemExec::terminate ()
487 ::pthread_mutex_lock(&write_lock);
493 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
494 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
497 TerminateProcess(pid->hProcess, 0xf291);
499 CloseHandle(pid->hThread);
500 CloseHandle(pid->hProcess);
501 destroy_pipe(stdinP);
502 destroy_pipe(stdoutP);
503 destroy_pipe(stderrP);
507 ::pthread_mutex_unlock(&write_lock);
511 SystemExec::wait (int options)
513 while (is_running()) {
514 WaitForSingleObject(pid->hProcess, 40);
520 SystemExec::is_running ()
522 if (!pid) return false;
524 if (GetExitCodeProcess(pid->hProcess, &exit_code)) {
525 if (exit_code == STILL_ACTIVE) return true;
531 SystemExec::start (StdErrMode stderr_mode, const char * /*vfork_exec_wrapper*/)
533 char* working_dir = 0;
535 if (pid) { return 0; }
537 pid = new PROCESS_INFORMATION;
538 memset(pid, 0, sizeof(PROCESS_INFORMATION));
540 create_pipe(stdinP, true);
541 create_pipe(stdoutP, false);
543 if (stderr_mode == MergeWithStdin) {
544 /* merge stout & stderr */
545 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
546 } else if (stderr_mode == IgnoreAndClose) {
547 //TODO read/flush this pipe or close it...
548 create_pipe(stderrP, false);
550 //TODO: keep stderr of this process mode.
553 bool success = false;
554 STARTUPINFOA startupInfo = { sizeof(STARTUPINFO), 0, 0, 0,
555 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
556 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
558 STARTF_USESTDHANDLES,
560 stdinP[0], stdoutP[1], stderrP[1]
563 success = CreateProcess(0, w_args,
564 0, 0, /* bInheritHandles = */ TRUE,
565 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
570 if (stdinP[0] != INVALID_HANDLE_VALUE) {
571 CloseHandle(stdinP[0]);
572 stdinP[0] = INVALID_HANDLE_VALUE;
574 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
575 CloseHandle(stdoutP[1]);
576 stdoutP[1] = INVALID_HANDLE_VALUE;
578 if (stderrP[1] != INVALID_HANDLE_VALUE) {
579 CloseHandle(stderrP[1]);
580 stderrP[1] = INVALID_HANDLE_VALUE;
584 CloseHandle(pid->hThread);
585 CloseHandle(pid->hProcess);
586 destroy_pipe(stdinP);
587 destroy_pipe(stdoutP);
588 destroy_pipe(stderrP);
594 int rv = pthread_create (&thread_id_tt, NULL, interposer_thread, this);
606 SystemExec::output_interposer()
610 #if 0 // untested code to set up nonblocking
612 ioctlsocket(stdoutP[0], FIONBIO, &l);
615 #if 0 // for non-blocking pipes..
616 DWORD bytesAvail = 0;
617 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
618 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
620 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
621 if (!ReadFile(stdoutP[0], data, BUFSIZ - 1, &bytesRead, 0)) {
622 DWORD err = GetLastError();
623 if (err == ERROR_IO_PENDING) continue;
626 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
628 ReadStdout(data, bytesRead); /* EMIT SIGNAL */
630 Terminated(); /* EMIT SIGNAL */
635 SystemExec::close_stdin()
637 if (stdinP[0] != INVALID_HANDLE_VALUE) FlushFileBuffers (stdinP[0]);
638 if (stdinP[1] != INVALID_HANDLE_VALUE) FlushFileBuffers (stdinP[1]);
640 destroy_pipe (stdinP);
644 SystemExec::write_to_stdin (const void* data, size_t bytes)
648 ::pthread_mutex_lock (&write_lock);
652 if (!WriteFile (stdinP[1], &((const char*)data)[c], bytes - c, &r, NULL)) {
653 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
657 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
663 ::pthread_mutex_unlock(&write_lock);
668 /* end windows process */
670 /* UNIX/POSIX process */
672 extern char **environ;
675 SystemExec::make_envp()
678 envp = (char **) calloc(1, sizeof(char*));
679 /* copy current environment */
680 for (i = 0; environ[i]; ++i) {
681 envp[i] = strdup(environ[i]);
682 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
688 SystemExec::make_argp(std::string args)
694 char *carg = strdup(args.c_str());
696 argp = (char **) malloc((argn + 1) * sizeof(char *));
697 if (argp == (char **) 0) {
702 argp[0] = strdup(cmd.c_str());
704 /* TODO: quotations and escapes
705 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
707 * It's actually not needed. All relevant invocations specify 'argp' directly.
708 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
709 * nor arguments with white-space.
711 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
714 argp[argn++] = strdup(cp1);
716 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
720 argp[argn++] = strdup(cp1);
721 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
723 argp[argn] = (char *) 0;
728 SystemExec::terminate ()
730 ::pthread_mutex_lock(&write_lock);
732 /* close stdin in an attempt to get the child to exit cleanly.
743 /* if pid is non-zero, the child task is still executing (i.e. it did
744 * not exit in response to stdin being closed). try to kill it.
748 ::kill(pid, SIGTERM);
754 /* if pid is non-zero, the child task is STILL executing after being
755 * sent SIGTERM. Act tough ... send SIGKILL
759 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
760 ::kill(pid, SIGKILL);
764 if (thread_active) pthread_join(thread_id_tt, NULL);
765 thread_active = false;
767 ::pthread_mutex_unlock(&write_lock);
771 SystemExec::wait (int options)
776 if (pid == 0) return -1;
778 ret = waitpid (pid, &status, options);
781 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
786 if (errno == ECHILD) {
787 /* no currently running children, reset pid */
790 } /* else the process is still running */
796 SystemExec::is_running ()
802 if (::waitpid (pid, &status, WNOHANG)==0) {
809 SystemExec::start (StdErrMode stderr_mode, const char *vfork_exec_wrapper)
817 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
818 /* Something unexpected went wrong creating a pipe. */
836 /* check if execve was successful. */
840 ssize_t n = ::read (pok[0], &buf, 1);
842 /* child process returned from execve */
851 } else if (n == -1) {
852 if (errno==EAGAIN || errno==EINTR) {
860 /* child started successfully */
865 int rv = pthread_create (&thread_id_tt, NULL, interposer_thread, this);
873 return 0; /* all systems go - return to main */
877 /* child process - exec external process */
879 ::fcntl (pok[1], F_SETFD, FD_CLOEXEC);
882 if (pin[0] != STDIN_FILENO) {
883 ::dup2 (pin[0], STDIN_FILENO);
887 if (pout[1] != STDOUT_FILENO) {
888 ::dup2 (pout[1], STDOUT_FILENO);
891 if (stderr_mode == MergeWithStdin) {
892 /* merge STDERR into output */
893 if (pout[1] != STDERR_FILENO) {
894 ::dup2(pout[1], STDERR_FILENO);
896 } else if (stderr_mode == IgnoreAndClose) {
898 ::close(STDERR_FILENO);
899 } else { /* stderr_mode == ShareWithParent */
901 #if defined __APPLE__&& defined ASL_LOG_DESCRIPTOR_WRITE
902 ::close(STDERR_FILENO);
903 stderr_mode = IgnoreAndClose; // for vfork
907 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
916 sigset (SIGPIPE, SIG_DFL);
918 signal (SIGPIPE, SIG_DFL);
920 if (!vfork_exec_wrapper) {
921 error << _("Cannot start external process, no vfork wrapper") << endmsg;
925 int good_fds[2] = { pok[1], -1 };
926 close_allv(good_fds);
928 ::execve(argp[0], argp, envp);
930 #else /* ! NO_VFORK */
932 /* XXX this should be done before vfork()
933 * calling malloc here only increases the time vfork() blocks
936 for (int i = 0; argp[i]; ++i) { argn++; }
938 argx = (char **) malloc ((argn + 10) * sizeof(char*));
939 argx[0] = strdup (vfork_exec_wrapper);
941 #define FDARG(NUM, FDN) \
942 argx[NUM] = (char*) calloc(6, sizeof(char)); snprintf(argx[NUM], 6, "%d", FDN);
950 FDARG (7, stderr_mode)
953 for (int i = 0; argp[i]; ++i) {
958 ::execve (argx[0], argx, envp);
961 /* if we reach here something went wrong.. */
963 (void) ::write (pok[1], &buf, 1);
970 SystemExec::output_interposer ()
977 ioctl (rfd, FIONBIO, &l); // set non-blocking I/O
979 for (;fcntl (rfd, F_GETFL) != -1;) {
980 r = read (rfd, buf, BUFSIZ - 1);
981 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
988 int rv = select (1, &rfds, NULL, NULL, &tv);
998 std::string rv = std::string (buf, r);
999 ReadStdout (rv, r); /* EMIT SIGNAL */
1001 Terminated (); /* EMIT SIGNAL */
1006 SystemExec::close_stdin()
1018 SystemExec::write_to_stdin (const void* data, size_t bytes)
1022 ::pthread_mutex_lock (&write_lock);
1027 r = ::write (pin[1], &((const char*)data)[c], bytes - c);
1028 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
1032 if ((size_t) r != (bytes-c)) {
1033 ::pthread_mutex_unlock(&write_lock);
1041 ::pthread_mutex_unlock(&write_lock);
1045 #endif // end UNIX process