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 */
155 SystemExec::SystemExec (std::string c, std::string a)
158 pthread_mutex_init(&write_lock, NULL);
165 #ifdef PLATFORM_WINDOWS
166 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
167 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
168 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
174 SystemExec::SystemExec (std::string c, char **a)
177 pthread_mutex_init(&write_lock, NULL);
183 #ifdef PLATFORM_WINDOWS
184 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
185 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
186 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
192 SystemExec::~SystemExec ()
196 for (int i=0;envp[i];++i) {
202 for (int i=0;argp[i];++i) {
207 #ifdef PLATFORM_WINDOWS
208 if (w_args) free(w_args);
210 pthread_mutex_destroy(&write_lock);
214 interposer_thread (void *arg) {
215 SystemExec *sex = static_cast<SystemExec *>(arg);
216 sex->output_interposer();
221 #ifdef PLATFORM_WINDOWS /* Windows Process */
223 /* HELPER FUNCTIONS */
225 static void create_pipe (HANDLE *pipe, bool in) {
226 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
229 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
230 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
232 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
233 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
235 CloseHandle(tmpHandle);
238 static void destroy_pipe (HANDLE pipe[2]) {
239 if (pipe[0] != INVALID_HANDLE_VALUE) {
240 CloseHandle(pipe[0]);
241 pipe[0] = INVALID_HANDLE_VALUE;
243 if (pipe[1] != INVALID_HANDLE_VALUE) {
244 CloseHandle(pipe[1]);
245 pipe[1] = INVALID_HANDLE_VALUE;
249 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
251 DWORD currentProcId = 0;
252 GetWindowThreadProcessId(hwnd, ¤tProcId);
253 if (currentProcId == (DWORD)procId)
254 PostMessage(hwnd, WM_CLOSE, 0, 0);
261 SystemExec::make_envp() {
262 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
266 SystemExec::make_wargs(char **a) {
267 std::string wa = cmd;
268 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
269 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
271 while (tmp && *tmp) {
273 std::string arg(*tmp);
274 size_t start_pos = 0;
275 while((start_pos = arg.find("\\", start_pos)) != std::string::npos) {
276 arg.replace(start_pos, 1, "\\\\");
283 w_args = strdup(wa.c_str());
287 SystemExec::make_argp(std::string args) {
288 std::string wa = cmd;
289 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
290 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
293 w_args = strdup(wa.c_str());
297 SystemExec::terminate ()
299 ::pthread_mutex_lock(&write_lock);
305 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
306 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
309 TerminateProcess(pid->hProcess, 0xf291);
311 CloseHandle(pid->hThread);
312 CloseHandle(pid->hProcess);
313 destroy_pipe(stdinP);
314 destroy_pipe(stdoutP);
315 destroy_pipe(stderrP);
319 ::pthread_mutex_unlock(&write_lock);
323 SystemExec::wait (int options)
325 while (is_running()) {
326 WaitForSingleObject(pid->hProcess, INFINITE);
333 SystemExec::is_running ()
335 return pid?true:false;
339 SystemExec::start (int stderr_mode, const char * /*vfork_exec_wrapper*/)
341 char* working_dir = 0;
343 if (pid) { return 0; }
345 pid = new PROCESS_INFORMATION;
346 memset(pid, 0, sizeof(PROCESS_INFORMATION));
348 create_pipe(stdinP, true);
349 create_pipe(stdoutP, false);
351 if (stderr_mode == 2) {
352 /* merge stout & stderr */
353 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
354 } else if (stderr_mode == 1) {
355 //TODO read/flush this pipe or close it...
356 create_pipe(stderrP, false);
358 //TODO: keep stderr of this process mode.
361 bool success = false;
362 STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
363 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
364 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
366 STARTF_USESTDHANDLES,
368 stdinP[0], stdoutP[1], stderrP[1]
371 success = CreateProcess(0, w_args,
372 0, 0, /* bInheritHandles = */ TRUE,
373 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
378 if (stdinP[0] != INVALID_HANDLE_VALUE) {
379 CloseHandle(stdinP[0]);
380 stdinP[0] = INVALID_HANDLE_VALUE;
382 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
383 CloseHandle(stdoutP[1]);
384 stdoutP[1] = INVALID_HANDLE_VALUE;
386 if (stderrP[1] != INVALID_HANDLE_VALUE) {
387 CloseHandle(stderrP[1]);
388 stderrP[1] = INVALID_HANDLE_VALUE;
392 CloseHandle(pid->hThread);
393 CloseHandle(pid->hProcess);
394 destroy_pipe(stdinP);
395 destroy_pipe(stdoutP);
396 destroy_pipe(stderrP);
402 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
414 SystemExec::output_interposer()
418 #if 0 // untested code to set up nonblocking
420 ioctlsocket(stdoutP[0], FIONBIO, &l);
423 #if 0 // for non-blocking pipes..
424 DWORD bytesAvail = 0;
425 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
426 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
428 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
429 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) {
430 DWORD err = GetLastError();
431 if (err == ERROR_IO_PENDING) continue;
434 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
436 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
438 Terminated();/* EMIT SIGNAL */
442 SystemExec::close_stdin()
444 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
445 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
447 destroy_pipe(stdinP);
451 SystemExec::write_to_stdin(std::string d, size_t len)
456 ::pthread_mutex_lock(&write_lock);
464 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
465 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
469 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
475 ::pthread_mutex_unlock(&write_lock);
480 /* end windows process */
482 /* UNIX/POSIX process */
484 extern char **environ;
486 SystemExec::make_envp() {
488 envp = (char **) calloc(1, sizeof(char*));
489 /* copy current environment */
490 for (i=0;environ[i];++i) {
491 envp[i] = strdup(environ[i]);
492 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
498 SystemExec::make_argp(std::string args) {
503 char *carg = strdup(args.c_str());
505 argp = (char **) malloc((argn + 1) * sizeof(char *));
506 if (argp == (char **) 0) {
511 argp[0] = strdup(cmd.c_str());
513 /* TODO: quotations and escapes
514 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
516 * It's actually not needed. All relevant invocations specify 'argp' directly.
517 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
518 * nor arguments with white-space.
520 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
523 argp[argn++] = strdup(cp1);
525 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
529 argp[argn++] = strdup(cp1);
530 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
532 argp[argn] = (char *) 0;
539 SystemExec::terminate ()
541 ::pthread_mutex_lock(&write_lock);
543 /* close stdin in an attempt to get the child to exit cleanly.
554 /* if pid is non-zero, the child task is still executing (i.e. it did
555 * not exit in response to stdin being closed). try to kill it.
559 ::kill(pid, SIGTERM);
565 /* if pid is non-zero, the child task is STILL executing after being
566 * sent SIGTERM. Act tough ... send SIGKILL
570 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
571 ::kill(pid, SIGKILL);
575 if (thread_active) pthread_join(thread_id_tt, NULL);
576 thread_active = false;
577 ::pthread_mutex_unlock(&write_lock);
581 SystemExec::wait (int options)
586 if (pid==0) return -1;
588 ret = waitpid (pid, &status, options);
591 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
596 if (errno == ECHILD) {
597 /* no currently running children, reset pid */
600 } /* else the process is still running */
606 SystemExec::is_running ()
609 if (pid==0) return false;
610 if (::waitpid(pid, &status, WNOHANG)==0) return true;
615 SystemExec::start (int stderr_mode, const char *vfork_exec_wrapper)
618 return 0; // mmh what to return here?
622 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
623 /* Something unexpected went wrong creating a pipe. */
641 /* check if execve was successful. */
645 ssize_t n = ::read(pok[0], &buf, 1 );
647 /* child process returned from execve */
656 } else if ( n==-1 ) {
657 if ( errno==EAGAIN || errno==EINTR )
663 /* child started successfully */
667 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
675 return 0; /* all systems go - return to main */
679 /* child process - exec external process */
681 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
684 if (pin[0] != STDIN_FILENO) {
685 ::dup2(pin[0], STDIN_FILENO);
689 if (pout[1] != STDOUT_FILENO) {
690 ::dup2(pout[1], STDOUT_FILENO);
693 if (stderr_mode == 2) {
694 /* merge STDERR into output */
695 if (pout[1] != STDERR_FILENO) {
696 ::dup2(pout[1], STDERR_FILENO);
698 } else if (stderr_mode == 1) {
700 ::close(STDERR_FILENO);
705 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
714 sigset(SIGPIPE, SIG_DFL);
716 signal(SIGPIPE, SIG_DFL);
719 int good_fds[2] = { pok[1], -1 };
720 close_allv(good_fds);
722 ::execve(argp[0], argp, envp);
723 /* if we reach here something went wrong.. */
725 (void) ::write(pok[1], &buf, 1 );
731 /* XXX this should be done before vfork()
732 * calling malloc here only increases the time vfork() blocks
735 for (int i=0;argp[i];++i) { argn++; }
736 char **argx = (char **) malloc((argn + 10) * sizeof(char *));
737 argx[0] = strdup(vfork_exec_wrapper); // XXX
739 #define FDARG(NUM, FDN) \
740 argx[NUM] = (char*) calloc(6, sizeof(char)); snprintf(argx[NUM], 6, "%d", FDN);
748 FDARG(7, stderr_mode)
751 for (int i=0;argp[i];++i) {
756 ::execve(argx[0], argx, envp);
758 /* if we reach here something went wrong.. */
760 (void) ::write(pok[1], &buf, 1 );
768 SystemExec::output_interposer()
775 ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
777 for (;fcntl(rfd, F_GETFL)!=-1;) {
778 r = read(rfd, buf, sizeof(buf));
779 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
787 std::string rv = std::string(buf,r); // TODO: check allocation strategy
788 ReadStdout(rv, r);/* EMIT SIGNAL */
790 Terminated();/* EMIT SIGNAL */
794 SystemExec::close_stdin()
796 if (pin[1]<0) return;
804 SystemExec::write_to_stdin(std::string d, size_t len)
809 ::pthread_mutex_lock(&write_lock);
818 r=::write(pin[1], data+c, len-c);
819 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
823 if ((size_t) r != (len-c)) {
824 ::pthread_mutex_unlock(&write_lock);
832 ::pthread_mutex_unlock(&write_lock);
836 #endif // end UNIX process