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>
49 #include "pbd/system_exec.h"
54 static void * interposer_thread (void *arg);
55 static void close_fd (int& fd) { if (fd >= 0) ::close (fd); fd = -1; }
57 #if (!defined PLATFORM_WINDOWS && defined NO_VFORK)
59 * This function was part of libasyncns.
61 * Copyright 2005-2008 Lennart Poettering
63 static int close_allv(const int except_fds[]) {
73 if ((d = opendir("/proc/self/fd"))) {
76 while ((de = readdir(d))) {
82 if (de->d_name[0] == '.')
86 l = strtol(de->d_name, &e, 10);
87 if (errno != 0 || !e || *e) {
108 for (i = 0; except_fds[i] >= 0; i++)
109 if (except_fds[i] == fd) {
133 if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
136 for (fd = 0; fd < (int) rl.rlim_max; fd++) {
142 for (i = 0; except_fds[i] >= 0; i++)
143 if (except_fds[i] == fd)
146 if (close(fd) < 0 && errno != EBADF)
152 #endif /* not on windows, nor vfork */
157 pthread_mutex_init(&write_lock, NULL);
163 #ifdef PLATFORM_WINDOWS
164 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
165 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
166 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
170 SystemExec::SystemExec (std::string c, std::string a)
180 SystemExec::SystemExec (std::string c, char **a)
185 #ifdef PLATFORM_WINDOWS
191 SystemExec::SystemExec (std::string command, const std::map<char, std::string> subs)
194 make_argp_escaped(command, subs);
196 // cmd = strdup(argp[0]);
201 SystemExec::make_argp_escaped(std::string command, const std::map<char, std::string> subs)
207 std::string arg = "";
209 argp = (char **) malloc(sizeof(char *));
211 for (i = 0; i <= command.length(); i++) { // include terminating '\0'
212 char c = command.c_str()[i];
217 // still in quotes - just copy
222 c = command.c_str()[++i];
223 if (c == '%' || c == '\0') {
224 // "%%", "%" at end-of-string => "%"
227 // search subs for string to substitute for char
228 std::map<char, std::string>::const_iterator s = subs.find(c);
229 if (s != subs.end()) {
230 // found substitution
233 // not a valid substitution, just copy
240 c = command.c_str()[++i];
243 case '"' : arg += c; break; // "\\", "\" at end-of-string => "\"
245 case '\\': arg += '\\'; break;
246 default : arg += '\\'; arg += c; break;
255 if (arg.length() > 0) {
256 // if there wasn't already a space or tab, start a new parameter
257 argp = (char **) realloc(argp, (n + 2) * sizeof(char *));
258 argp[n++] = strdup (arg.c_str());
273 SystemExec::~SystemExec ()
277 for (int i=0;envp[i];++i) {
283 for (int i=0;argp[i];++i) {
288 #ifdef PLATFORM_WINDOWS
289 if (w_args) free(w_args);
291 pthread_mutex_destroy(&write_lock);
295 interposer_thread (void *arg) {
296 SystemExec *sex = static_cast<SystemExec *>(arg);
297 sex->output_interposer();
302 #ifdef PLATFORM_WINDOWS /* Windows Process */
304 /* HELPER FUNCTIONS */
306 static void create_pipe (HANDLE *pipe, bool in) {
307 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
310 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
311 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
313 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
314 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
316 CloseHandle(tmpHandle);
319 static void destroy_pipe (HANDLE pipe[2]) {
320 if (pipe[0] != INVALID_HANDLE_VALUE) {
321 CloseHandle(pipe[0]);
322 pipe[0] = INVALID_HANDLE_VALUE;
324 if (pipe[1] != INVALID_HANDLE_VALUE) {
325 CloseHandle(pipe[1]);
326 pipe[1] = INVALID_HANDLE_VALUE;
330 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
332 DWORD currentProcId = 0;
333 GetWindowThreadProcessId(hwnd, ¤tProcId);
334 if (currentProcId == (DWORD)procId)
335 PostMessage(hwnd, WM_CLOSE, 0, 0);
342 SystemExec::make_envp() {
343 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
347 SystemExec::make_wargs(char **a) {
348 std::string wa = cmd;
349 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
350 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
352 while (tmp && *tmp) {
354 std::string arg(*tmp);
355 size_t start_pos = 0;
356 while((start_pos = arg.find("\\", start_pos)) != std::string::npos) {
357 arg.replace(start_pos, 1, "\\\\");
364 w_args = strdup(wa.c_str());
368 SystemExec::make_argp(std::string args) {
369 std::string wa = cmd;
370 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
371 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
374 w_args = strdup(wa.c_str());
378 SystemExec::terminate ()
380 ::pthread_mutex_lock(&write_lock);
386 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
387 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
390 TerminateProcess(pid->hProcess, 0xf291);
392 CloseHandle(pid->hThread);
393 CloseHandle(pid->hProcess);
394 destroy_pipe(stdinP);
395 destroy_pipe(stdoutP);
396 destroy_pipe(stderrP);
400 ::pthread_mutex_unlock(&write_lock);
404 SystemExec::wait (int options)
406 while (is_running()) {
407 WaitForSingleObject(pid->hProcess, INFINITE);
414 SystemExec::is_running ()
416 return pid?true:false;
420 SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
422 char* working_dir = 0;
424 if (pid) { return 0; }
426 pid = new PROCESS_INFORMATION;
427 memset(pid, 0, sizeof(PROCESS_INFORMATION));
429 create_pipe(stdinP, true);
430 create_pipe(stdoutP, false);
432 if (stderr_mode == 2) {
433 /* merge stout & stderr */
434 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
435 } else if (stderr_mode == 1) {
436 //TODO read/flush this pipe or close it...
437 create_pipe(stderrP, false);
439 //TODO: keep stderr of this process mode.
442 bool success = false;
443 STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
444 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
445 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
447 STARTF_USESTDHANDLES,
449 stdinP[0], stdoutP[1], stderrP[1]
452 success = CreateProcess(0, w_args,
453 0, 0, /* bInheritHandles = */ TRUE,
454 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
459 if (stdinP[0] != INVALID_HANDLE_VALUE) {
460 CloseHandle(stdinP[0]);
461 stdinP[0] = INVALID_HANDLE_VALUE;
463 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
464 CloseHandle(stdoutP[1]);
465 stdoutP[1] = INVALID_HANDLE_VALUE;
467 if (stderrP[1] != INVALID_HANDLE_VALUE) {
468 CloseHandle(stderrP[1]);
469 stderrP[1] = INVALID_HANDLE_VALUE;
473 CloseHandle(pid->hThread);
474 CloseHandle(pid->hProcess);
475 destroy_pipe(stdinP);
476 destroy_pipe(stdoutP);
477 destroy_pipe(stderrP);
483 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
495 SystemExec::output_interposer()
499 #if 0 // untested code to set up nonblocking
501 ioctlsocket(stdoutP[0], FIONBIO, &l);
504 #if 0 // for non-blocking pipes..
505 DWORD bytesAvail = 0;
506 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
507 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
509 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
510 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) {
511 DWORD err = GetLastError();
512 if (err == ERROR_IO_PENDING) continue;
515 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
517 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
519 Terminated();/* EMIT SIGNAL */
523 SystemExec::close_stdin()
525 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
526 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
528 destroy_pipe(stdinP);
532 SystemExec::write_to_stdin(std::string d, size_t len)
537 ::pthread_mutex_lock(&write_lock);
545 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
546 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
550 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
556 ::pthread_mutex_unlock(&write_lock);
561 /* end windows process */
563 /* UNIX/POSIX process */
565 extern char **environ;
567 SystemExec::make_envp() {
569 envp = (char **) calloc(1, sizeof(char*));
570 /* copy current environment */
571 for (i=0;environ[i];++i) {
572 envp[i] = strdup(environ[i]);
573 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
579 SystemExec::make_argp(std::string args) {
584 char *carg = strdup(args.c_str());
586 argp = (char **) malloc((argn + 1) * sizeof(char *));
587 if (argp == (char **) 0) {
592 argp[0] = strdup(cmd.c_str());
594 /* TODO: quotations and escapes
595 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
597 * It's actually not needed. All relevant invocations specify 'argp' directly.
598 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
599 * nor arguments with white-space.
601 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
604 argp[argn++] = strdup(cp1);
606 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
610 argp[argn++] = strdup(cp1);
611 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
613 argp[argn] = (char *) 0;
620 SystemExec::terminate ()
622 ::pthread_mutex_lock(&write_lock);
624 /* close stdin in an attempt to get the child to exit cleanly.
635 /* if pid is non-zero, the child task is still executing (i.e. it did
636 * not exit in response to stdin being closed). try to kill it.
640 ::kill(pid, SIGTERM);
646 /* if pid is non-zero, the child task is STILL executing after being
647 * sent SIGTERM. Act tough ... send SIGKILL
651 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
652 ::kill(pid, SIGKILL);
656 if (thread_active) pthread_join(thread_id_tt, NULL);
657 thread_active = false;
658 ::pthread_mutex_unlock(&write_lock);
662 SystemExec::wait (int options)
667 if (pid==0) return -1;
669 ret = waitpid (pid, &status, options);
672 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
677 if (errno == ECHILD) {
678 /* no currently running children, reset pid */
681 } /* else the process is still running */
687 SystemExec::is_running ()
690 if (pid==0) return false;
691 if (::waitpid(pid, &status, WNOHANG)==0) return true;
696 SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
699 return 0; // mmh what to return here?
703 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
704 /* Something unexpected went wrong creating a pipe. */
722 /* check if execve was successful. */
726 ssize_t n = ::read(pok[0], &buf, 1 );
728 /* child process returned from execve */
737 } else if ( n==-1 ) {
738 if ( errno==EAGAIN || errno==EINTR )
744 /* child started successfully */
748 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
756 return 0; /* all systems go - return to main */
760 /* child process - exec external process */
762 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
765 if (pin[0] != STDIN_FILENO) {
766 ::dup2(pin[0], STDIN_FILENO);
770 if (pout[1] != STDOUT_FILENO) {
771 ::dup2(pout[1], STDOUT_FILENO);
774 if (stderr_mode == 2) {
775 /* merge STDERR into output */
776 if (pout[1] != STDERR_FILENO) {
777 ::dup2(pout[1], STDERR_FILENO);
779 } else if (stderr_mode == 1) {
781 ::close(STDERR_FILENO);
786 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
795 sigset(SIGPIPE, SIG_DFL);
797 signal(SIGPIPE, SIG_DFL);
800 int good_fds[2] = { pok[1], -1 };
801 close_allv(good_fds);
803 ::execve(argp[0], argp, envp);
804 /* if we reach here something went wrong.. */
806 (void) ::write(pok[1], &buf, 1 );
812 /* XXX this should be done before vfork()
813 * calling malloc here only increases the time vfork() blocks
816 for (int i=0;argp[i];++i) { argn++; }
817 char **argx = (char **) malloc((argn + 10) * sizeof(char *));
818 argx[0] = strdup(vfork_exec_wrapper); // XXX
820 #define FDARG(NUM, FDN) \
821 argx[NUM] = (char*) calloc(6, sizeof(char)); snprintf(argx[NUM], 6, "%d", FDN);
829 FDARG(7, stderr_mode)
832 for (int i=0;argp[i];++i) {
837 ::execve(argx[0], argx, envp);
839 /* if we reach here something went wrong.. */
841 (void) ::write(pok[1], &buf, 1 );
849 SystemExec::output_interposer()
856 ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
858 for (;fcntl(rfd, F_GETFL)!=-1;) {
859 r = read(rfd, buf, sizeof(buf));
860 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
868 std::string rv = std::string(buf,r); // TODO: check allocation strategy
869 ReadStdout(rv, r);/* EMIT SIGNAL */
871 Terminated();/* EMIT SIGNAL */
875 SystemExec::close_stdin()
877 if (pin[1]<0) return;
885 SystemExec::write_to_stdin(std::string d, size_t len)
890 ::pthread_mutex_lock(&write_lock);
899 r=::write(pin[1], data+c, len-c);
900 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
904 if ((size_t) r != (len-c)) {
905 ::pthread_mutex_unlock(&write_lock);
913 ::pthread_mutex_unlock(&write_lock);
917 #endif // end UNIX process