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());
272 std::cerr << "argv[" << n << "] == \"" << p << "\"" << std::endl;
278 SystemExec::~SystemExec ()
282 for (int i=0;envp[i];++i) {
288 for (int i=0;argp[i];++i) {
293 #ifdef PLATFORM_WINDOWS
294 if (w_args) free(w_args);
296 pthread_mutex_destroy(&write_lock);
300 interposer_thread (void *arg) {
301 SystemExec *sex = static_cast<SystemExec *>(arg);
302 sex->output_interposer();
307 #ifdef PLATFORM_WINDOWS /* Windows Process */
309 /* HELPER FUNCTIONS */
311 static void create_pipe (HANDLE *pipe, bool in) {
312 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
315 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
316 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
318 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
319 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
321 CloseHandle(tmpHandle);
324 static void destroy_pipe (HANDLE pipe[2]) {
325 if (pipe[0] != INVALID_HANDLE_VALUE) {
326 CloseHandle(pipe[0]);
327 pipe[0] = INVALID_HANDLE_VALUE;
329 if (pipe[1] != INVALID_HANDLE_VALUE) {
330 CloseHandle(pipe[1]);
331 pipe[1] = INVALID_HANDLE_VALUE;
335 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
337 DWORD currentProcId = 0;
338 GetWindowThreadProcessId(hwnd, ¤tProcId);
339 if (currentProcId == (DWORD)procId)
340 PostMessage(hwnd, WM_CLOSE, 0, 0);
347 SystemExec::make_envp() {
348 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
352 SystemExec::make_wargs(char **a) {
353 std::string wa = cmd;
354 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
355 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
357 while (tmp && *tmp) {
359 std::string arg(*tmp);
360 size_t start_pos = 0;
361 while((start_pos = arg.find("\\", start_pos)) != std::string::npos) {
362 arg.replace(start_pos, 1, "\\\\");
369 w_args = strdup(wa.c_str());
373 SystemExec::make_argp(std::string args) {
374 std::string wa = cmd;
375 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
376 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
379 w_args = strdup(wa.c_str());
383 SystemExec::terminate ()
385 ::pthread_mutex_lock(&write_lock);
391 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
392 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
395 TerminateProcess(pid->hProcess, 0xf291);
397 CloseHandle(pid->hThread);
398 CloseHandle(pid->hProcess);
399 destroy_pipe(stdinP);
400 destroy_pipe(stdoutP);
401 destroy_pipe(stderrP);
405 ::pthread_mutex_unlock(&write_lock);
409 SystemExec::wait (int options)
411 while (is_running()) {
412 WaitForSingleObject(pid->hProcess, INFINITE);
419 SystemExec::is_running ()
421 return pid?true:false;
425 SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
427 char* working_dir = 0;
429 if (pid) { return 0; }
431 pid = new PROCESS_INFORMATION;
432 memset(pid, 0, sizeof(PROCESS_INFORMATION));
434 create_pipe(stdinP, true);
435 create_pipe(stdoutP, false);
437 if (stderr_mode == 2) {
438 /* merge stout & stderr */
439 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
440 } else if (stderr_mode == 1) {
441 //TODO read/flush this pipe or close it...
442 create_pipe(stderrP, false);
444 //TODO: keep stderr of this process mode.
447 bool success = false;
448 STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
449 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
450 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
452 STARTF_USESTDHANDLES,
454 stdinP[0], stdoutP[1], stderrP[1]
457 success = CreateProcess(0, w_args,
458 0, 0, /* bInheritHandles = */ TRUE,
459 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
464 if (stdinP[0] != INVALID_HANDLE_VALUE) {
465 CloseHandle(stdinP[0]);
466 stdinP[0] = INVALID_HANDLE_VALUE;
468 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
469 CloseHandle(stdoutP[1]);
470 stdoutP[1] = INVALID_HANDLE_VALUE;
472 if (stderrP[1] != INVALID_HANDLE_VALUE) {
473 CloseHandle(stderrP[1]);
474 stderrP[1] = INVALID_HANDLE_VALUE;
478 CloseHandle(pid->hThread);
479 CloseHandle(pid->hProcess);
480 destroy_pipe(stdinP);
481 destroy_pipe(stdoutP);
482 destroy_pipe(stderrP);
488 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
500 SystemExec::output_interposer()
504 #if 0 // untested code to set up nonblocking
506 ioctlsocket(stdoutP[0], FIONBIO, &l);
509 #if 0 // for non-blocking pipes..
510 DWORD bytesAvail = 0;
511 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
512 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
514 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
515 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) {
516 DWORD err = GetLastError();
517 if (err == ERROR_IO_PENDING) continue;
520 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
522 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
524 Terminated();/* EMIT SIGNAL */
528 SystemExec::close_stdin()
530 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
531 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
533 destroy_pipe(stdinP);
537 SystemExec::write_to_stdin(std::string d, size_t len)
542 ::pthread_mutex_lock(&write_lock);
550 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
551 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
555 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
561 ::pthread_mutex_unlock(&write_lock);
566 /* end windows process */
568 /* UNIX/POSIX process */
570 extern char **environ;
572 SystemExec::make_envp() {
574 envp = (char **) calloc(1, sizeof(char*));
575 /* copy current environment */
576 for (i=0;environ[i];++i) {
577 envp[i] = strdup(environ[i]);
578 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
584 SystemExec::make_argp(std::string args) {
589 char *carg = strdup(args.c_str());
591 argp = (char **) malloc((argn + 1) * sizeof(char *));
592 if (argp == (char **) 0) {
597 argp[0] = strdup(cmd.c_str());
599 /* TODO: quotations and escapes
600 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
602 * It's actually not needed. All relevant invocations specify 'argp' directly.
603 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
604 * nor arguments with white-space.
606 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
609 argp[argn++] = strdup(cp1);
611 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
615 argp[argn++] = strdup(cp1);
616 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
618 argp[argn] = (char *) 0;
625 SystemExec::terminate ()
627 ::pthread_mutex_lock(&write_lock);
629 /* close stdin in an attempt to get the child to exit cleanly.
640 /* if pid is non-zero, the child task is still executing (i.e. it did
641 * not exit in response to stdin being closed). try to kill it.
645 ::kill(pid, SIGTERM);
651 /* if pid is non-zero, the child task is STILL executing after being
652 * sent SIGTERM. Act tough ... send SIGKILL
656 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
657 ::kill(pid, SIGKILL);
661 if (thread_active) pthread_join(thread_id_tt, NULL);
662 thread_active = false;
663 ::pthread_mutex_unlock(&write_lock);
667 SystemExec::wait (int options)
672 if (pid==0) return -1;
674 ret = waitpid (pid, &status, options);
677 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
682 if (errno == ECHILD) {
683 /* no currently running children, reset pid */
686 } /* else the process is still running */
692 SystemExec::is_running ()
695 if (pid==0) return false;
696 if (::waitpid(pid, &status, WNOHANG)==0) return true;
701 SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
704 return 0; // mmh what to return here?
708 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
709 /* Something unexpected went wrong creating a pipe. */
727 /* check if execve was successful. */
731 ssize_t n = ::read(pok[0], &buf, 1 );
733 /* child process returned from execve */
742 } else if ( n==-1 ) {
743 if ( errno==EAGAIN || errno==EINTR )
749 /* child started successfully */
753 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
761 return 0; /* all systems go - return to main */
765 /* child process - exec external process */
767 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
770 if (pin[0] != STDIN_FILENO) {
771 ::dup2(pin[0], STDIN_FILENO);
775 if (pout[1] != STDOUT_FILENO) {
776 ::dup2(pout[1], STDOUT_FILENO);
779 if (stderr_mode == 2) {
780 /* merge STDERR into output */
781 if (pout[1] != STDERR_FILENO) {
782 ::dup2(pout[1], STDERR_FILENO);
784 } else if (stderr_mode == 1) {
786 ::close(STDERR_FILENO);
791 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
800 sigset(SIGPIPE, SIG_DFL);
802 signal(SIGPIPE, SIG_DFL);
805 int good_fds[2] = { pok[1], -1 };
806 close_allv(good_fds);
808 ::execve(argp[0], argp, envp);
809 /* if we reach here something went wrong.. */
811 (void) ::write(pok[1], &buf, 1 );
817 /* XXX this should be done before vfork()
818 * calling malloc here only increases the time vfork() blocks
821 for (int i=0;argp[i];++i) { argn++; }
822 char **argx = (char **) malloc((argn + 10) * sizeof(char *));
823 argx[0] = strdup(vfork_exec_wrapper); // XXX
825 #define FDARG(NUM, FDN) \
826 argx[NUM] = (char*) calloc(6, sizeof(char)); snprintf(argx[NUM], 6, "%d", FDN);
834 FDARG(7, stderr_mode)
837 for (int i=0;argp[i];++i) {
842 ::execve(argx[0], argx, envp);
844 /* if we reach here something went wrong.. */
846 (void) ::write(pok[1], &buf, 1 );
854 SystemExec::output_interposer()
861 ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
863 for (;fcntl(rfd, F_GETFL)!=-1;) {
864 r = read(rfd, buf, sizeof(buf));
865 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
873 std::string rv = std::string(buf,r); // TODO: check allocation strategy
874 ReadStdout(rv, r);/* EMIT SIGNAL */
876 Terminated();/* EMIT SIGNAL */
880 SystemExec::close_stdin()
882 if (pin[1]<0) return;
890 SystemExec::write_to_stdin(std::string d, size_t len)
895 ::pthread_mutex_lock(&write_lock);
904 r=::write(pin[1], data+c, len-c);
905 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
909 if ((size_t) r != (len-c)) {
910 ::pthread_mutex_unlock(&write_lock);
918 ::pthread_mutex_unlock(&write_lock);
922 #endif // end UNIX process