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);
58 static void close_fd (int& fd) { if (fd >= 0) ::close (fd); fd = -1; }
60 #if (!defined PLATFORM_WINDOWS && defined NO_VFORK)
62 * This function was part of libasyncns.
64 * Copyright 2005-2008 Lennart Poettering
66 static int close_allv(const int except_fds[]) {
76 if ((d = opendir("/proc/self/fd"))) {
79 while ((de = readdir(d))) {
85 if (de->d_name[0] == '.')
89 l = strtol(de->d_name, &e, 10);
90 if (errno != 0 || !e || *e) {
111 for (i = 0; except_fds[i] >= 0; i++)
112 if (except_fds[i] == fd) {
136 if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
139 for (fd = 0; fd < (int) rl.rlim_max; fd++) {
145 for (i = 0; except_fds[i] >= 0; i++)
146 if (except_fds[i] == fd)
149 if (close(fd) < 0 && errno != EBADF)
155 #endif /* not on windows, nor vfork */
160 pthread_mutex_init(&write_lock, NULL);
166 #ifdef PLATFORM_WINDOWS
167 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
168 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
169 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
173 SystemExec::SystemExec (std::string c, std::string a)
183 SystemExec::SystemExec (std::string c, char **a)
188 #ifdef PLATFORM_WINDOWS
194 SystemExec::SystemExec (std::string command, const std::map<char, std::string> subs)
197 make_argp_escaped(command, subs);
198 if (!find_file_in_search_path (Searchpath (Glib::getenv ("PATH")), argp[0], cmd)) {
199 // not found in path - use as-is
203 // Glib::find_program_in_path () is only available in Glib >= 2.28
204 // cmd = Glib::find_program_in_path (argp[0]);
210 SystemExec::make_argp_escaped(std::string command, const std::map<char, std::string> subs)
216 std::string arg = "";
218 argp = (char **) malloc(sizeof(char *));
220 for (i = 0; i <= command.length(); i++) { // include terminating '\0'
221 char c = command.c_str()[i];
226 // still in quotes - just copy
231 c = command.c_str()[++i];
232 if (c == '%' || c == '\0') {
233 // "%%", "%" at end-of-string => "%"
236 // search subs for string to substitute for char
237 std::map<char, std::string>::const_iterator s = subs.find(c);
238 if (s != subs.end()) {
239 // found substitution
242 // not a valid substitution, just copy
249 c = command.c_str()[++i];
252 case '"' : arg += c; break; // "\\", "\" at end-of-string => "\"
254 case '\\': arg += '\\'; break;
255 default : arg += '\\'; arg += c; break;
264 if (arg.length() > 0) {
265 // if there wasn't already a space or tab, start a new parameter
266 argp = (char **) realloc(argp, (n + 2) * sizeof(char *));
267 argp[n++] = strdup (arg.c_str());
279 SystemExec::~SystemExec ()
283 for (int i=0;envp[i];++i) {
289 for (int i=0;argp[i];++i) {
294 #ifdef PLATFORM_WINDOWS
295 if (w_args) free(w_args);
297 pthread_mutex_destroy(&write_lock);
301 interposer_thread (void *arg) {
302 SystemExec *sex = static_cast<SystemExec *>(arg);
303 sex->output_interposer();
308 #ifdef PLATFORM_WINDOWS /* Windows Process */
310 /* HELPER FUNCTIONS */
312 static void create_pipe (HANDLE *pipe, bool in) {
313 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
316 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
317 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
319 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
320 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
322 CloseHandle(tmpHandle);
325 static void destroy_pipe (HANDLE pipe[2]) {
326 if (pipe[0] != INVALID_HANDLE_VALUE) {
327 CloseHandle(pipe[0]);
328 pipe[0] = INVALID_HANDLE_VALUE;
330 if (pipe[1] != INVALID_HANDLE_VALUE) {
331 CloseHandle(pipe[1]);
332 pipe[1] = INVALID_HANDLE_VALUE;
336 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
338 DWORD currentProcId = 0;
339 GetWindowThreadProcessId(hwnd, ¤tProcId);
340 if (currentProcId == (DWORD)procId)
341 PostMessage(hwnd, WM_CLOSE, 0, 0);
348 SystemExec::make_envp() {
349 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
353 SystemExec::make_wargs(char **a) {
354 std::string wa = cmd;
355 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
356 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
358 while (tmp && *tmp) {
360 std::string arg(*tmp);
361 size_t start_pos = 0;
362 while((start_pos = arg.find("\\", start_pos)) != std::string::npos) {
363 arg.replace(start_pos, 1, "\\\\");
370 w_args = strdup(wa.c_str());
374 SystemExec::make_argp(std::string args) {
375 std::string wa = cmd;
376 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
377 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
380 w_args = strdup(wa.c_str());
384 SystemExec::terminate ()
386 ::pthread_mutex_lock(&write_lock);
392 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
393 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
396 TerminateProcess(pid->hProcess, 0xf291);
398 CloseHandle(pid->hThread);
399 CloseHandle(pid->hProcess);
400 destroy_pipe(stdinP);
401 destroy_pipe(stdoutP);
402 destroy_pipe(stderrP);
406 ::pthread_mutex_unlock(&write_lock);
410 SystemExec::wait (int options)
412 while (is_running()) {
413 WaitForSingleObject(pid->hProcess, INFINITE);
420 SystemExec::is_running ()
422 return pid?true:false;
426 SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
428 char* working_dir = 0;
430 if (pid) { return 0; }
432 pid = new PROCESS_INFORMATION;
433 memset(pid, 0, sizeof(PROCESS_INFORMATION));
435 create_pipe(stdinP, true);
436 create_pipe(stdoutP, false);
438 if (stderr_mode == 2) {
439 /* merge stout & stderr */
440 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
441 } else if (stderr_mode == 1) {
442 //TODO read/flush this pipe or close it...
443 create_pipe(stderrP, false);
445 //TODO: keep stderr of this process mode.
448 bool success = false;
449 STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
450 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
451 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
453 STARTF_USESTDHANDLES,
455 stdinP[0], stdoutP[1], stderrP[1]
458 success = CreateProcess(0, w_args,
459 0, 0, /* bInheritHandles = */ TRUE,
460 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
465 if (stdinP[0] != INVALID_HANDLE_VALUE) {
466 CloseHandle(stdinP[0]);
467 stdinP[0] = INVALID_HANDLE_VALUE;
469 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
470 CloseHandle(stdoutP[1]);
471 stdoutP[1] = INVALID_HANDLE_VALUE;
473 if (stderrP[1] != INVALID_HANDLE_VALUE) {
474 CloseHandle(stderrP[1]);
475 stderrP[1] = INVALID_HANDLE_VALUE;
479 CloseHandle(pid->hThread);
480 CloseHandle(pid->hProcess);
481 destroy_pipe(stdinP);
482 destroy_pipe(stdoutP);
483 destroy_pipe(stderrP);
489 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
501 SystemExec::output_interposer()
505 #if 0 // untested code to set up nonblocking
507 ioctlsocket(stdoutP[0], FIONBIO, &l);
510 #if 0 // for non-blocking pipes..
511 DWORD bytesAvail = 0;
512 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
513 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
515 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
516 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) {
517 DWORD err = GetLastError();
518 if (err == ERROR_IO_PENDING) continue;
521 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
523 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
525 Terminated();/* EMIT SIGNAL */
529 SystemExec::close_stdin()
531 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
532 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
534 destroy_pipe(stdinP);
538 SystemExec::write_to_stdin(std::string d, size_t len)
543 ::pthread_mutex_lock(&write_lock);
551 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
552 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
556 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
562 ::pthread_mutex_unlock(&write_lock);
567 /* end windows process */
569 /* UNIX/POSIX process */
571 extern char **environ;
573 SystemExec::make_envp() {
575 envp = (char **) calloc(1, sizeof(char*));
576 /* copy current environment */
577 for (i=0;environ[i];++i) {
578 envp[i] = strdup(environ[i]);
579 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
585 SystemExec::make_argp(std::string args) {
590 char *carg = strdup(args.c_str());
592 argp = (char **) malloc((argn + 1) * sizeof(char *));
593 if (argp == (char **) 0) {
598 argp[0] = strdup(cmd.c_str());
600 /* TODO: quotations and escapes
601 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
603 * It's actually not needed. All relevant invocations specify 'argp' directly.
604 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
605 * nor arguments with white-space.
607 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
610 argp[argn++] = strdup(cp1);
612 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
616 argp[argn++] = strdup(cp1);
617 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
619 argp[argn] = (char *) 0;
626 SystemExec::terminate ()
628 ::pthread_mutex_lock(&write_lock);
630 /* close stdin in an attempt to get the child to exit cleanly.
641 /* if pid is non-zero, the child task is still executing (i.e. it did
642 * not exit in response to stdin being closed). try to kill it.
646 ::kill(pid, SIGTERM);
652 /* if pid is non-zero, the child task is STILL executing after being
653 * sent SIGTERM. Act tough ... send SIGKILL
657 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
658 ::kill(pid, SIGKILL);
662 if (thread_active) pthread_join(thread_id_tt, NULL);
663 thread_active = false;
664 ::pthread_mutex_unlock(&write_lock);
668 SystemExec::wait (int options)
673 if (pid==0) return -1;
675 ret = waitpid (pid, &status, options);
678 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
683 if (errno == ECHILD) {
684 /* no currently running children, reset pid */
687 } /* else the process is still running */
693 SystemExec::is_running ()
696 if (pid==0) return false;
697 if (::waitpid(pid, &status, WNOHANG)==0) return true;
702 SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
705 return 0; // mmh what to return here?
709 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
710 /* Something unexpected went wrong creating a pipe. */
728 /* check if execve was successful. */
732 ssize_t n = ::read(pok[0], &buf, 1 );
734 /* child process returned from execve */
743 } else if ( n==-1 ) {
744 if ( errno==EAGAIN || errno==EINTR )
750 /* child started successfully */
754 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
762 return 0; /* all systems go - return to main */
766 /* child process - exec external process */
768 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
771 if (pin[0] != STDIN_FILENO) {
772 ::dup2(pin[0], STDIN_FILENO);
776 if (pout[1] != STDOUT_FILENO) {
777 ::dup2(pout[1], STDOUT_FILENO);
780 if (stderr_mode == 2) {
781 /* merge STDERR into output */
782 if (pout[1] != STDERR_FILENO) {
783 ::dup2(pout[1], STDERR_FILENO);
785 } else if (stderr_mode == 1) {
787 ::close(STDERR_FILENO);
792 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
801 sigset(SIGPIPE, SIG_DFL);
803 signal(SIGPIPE, SIG_DFL);
806 int good_fds[2] = { pok[1], -1 };
807 close_allv(good_fds);
809 ::execve(argp[0], argp, envp);
810 /* if we reach here something went wrong.. */
812 (void) ::write(pok[1], &buf, 1 );
818 /* XXX this should be done before vfork()
819 * calling malloc here only increases the time vfork() blocks
822 for (int i=0;argp[i];++i) { argn++; }
823 char **argx = (char **) malloc((argn + 10) * sizeof(char *));
824 argx[0] = strdup(vfork_exec_wrapper); // XXX
826 #define FDARG(NUM, FDN) \
827 argx[NUM] = (char*) calloc(6, sizeof(char)); snprintf(argx[NUM], 6, "%d", FDN);
835 FDARG(7, stderr_mode)
838 for (int i=0;argp[i];++i) {
843 ::execve(argx[0], argx, envp);
845 /* if we reach here something went wrong.. */
847 (void) ::write(pok[1], &buf, 1 );
855 SystemExec::output_interposer()
862 ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
864 for (;fcntl(rfd, F_GETFL)!=-1;) {
865 r = read(rfd, buf, sizeof(buf));
866 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
874 std::string rv = std::string(buf,r); // TODO: check allocation strategy
875 ReadStdout(rv, r);/* EMIT SIGNAL */
877 Terminated();/* EMIT SIGNAL */
881 SystemExec::close_stdin()
883 if (pin[1]<0) return;
891 SystemExec::write_to_stdin(std::string d, size_t len)
896 ::pthread_mutex_lock(&write_lock);
905 r=::write(pin[1], data+c, len-c);
906 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
910 if ((size_t) r != (len-c)) {
911 ::pthread_mutex_unlock(&write_lock);
919 ::pthread_mutex_unlock(&write_lock);
923 #endif // end UNIX process