2 Copyright (C) 2010 Paul Davis
3 Copyright 2005-2008 Lennart Poettering
4 Author: Robin Gareus <robin@gareus.org>
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.
33 #ifdef PLATFORM_WINDOWS
37 #include <sys/types.h>
39 #include <sys/socket.h>
40 #include <sys/ioctl.h>
42 #include <sys/resource.h>
46 #include "system_exec.h"
49 void * interposer_thread (void *arg);
51 static void close_fd (int& fd) { if (fd >= 0) ::close (fd); fd = -1; }
53 #ifndef PLATFORM_WINDOWS
55 * This function was part of libasyncns.
57 * Copyright 2005-2008 Lennart Poettering
59 static int close_allv(const int except_fds[]) {
69 if ((d = opendir("/proc/self/fd"))) {
72 while ((de = readdir(d))) {
78 if (de->d_name[0] == '.')
82 l = strtol(de->d_name, &e, 10);
83 if (errno != 0 || !e || *e) {
104 for (i = 0; except_fds[i] >= 0; i++)
105 if (except_fds[i] == fd) {
129 if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
132 for (fd = 0; fd < (int) rl.rlim_max; fd++) {
138 for (i = 0; except_fds[i] >= 0; i++)
139 if (except_fds[i] == fd)
142 if (close(fd) < 0 && errno != EBADF)
148 #endif /* not on windows */
151 SystemExec::SystemExec (std::string c, std::string a)
154 pthread_mutex_init(&write_lock, NULL);
161 #ifdef PLATFORM_WINDOWS
162 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
163 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
164 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
170 SystemExec::SystemExec (std::string c, char **a)
173 pthread_mutex_init(&write_lock, NULL);
179 #ifdef PLATFORM_WINDOWS
180 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
181 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
182 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
188 SystemExec::~SystemExec ()
192 for (int i=0;envp[i];++i) {
198 for (int i=0;argp[i];++i) {
203 #ifdef PLATFORM_WINDOWS
204 if (w_args) free(w_args);
206 pthread_mutex_destroy(&write_lock);
210 interposer_thread (void *arg) {
211 SystemExec *sex = static_cast<SystemExec *>(arg);
212 sex->output_interposer();
217 #ifdef PLATFORM_WINDOWS /* Windows Process */
219 /* HELPER FUNCTIONS */
221 static void create_pipe (HANDLE *pipe, bool in) {
222 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
225 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
226 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
228 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
229 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
231 CloseHandle(tmpHandle);
234 static void destroy_pipe (HANDLE pipe[2]) {
235 if (pipe[0] != INVALID_HANDLE_VALUE) {
236 CloseHandle(pipe[0]);
237 pipe[0] = INVALID_HANDLE_VALUE;
239 if (pipe[1] != INVALID_HANDLE_VALUE) {
240 CloseHandle(pipe[1]);
241 pipe[1] = INVALID_HANDLE_VALUE;
245 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
247 DWORD currentProcId = 0;
248 GetWindowThreadProcessId(hwnd, ¤tProcId);
249 if (currentProcId == (DWORD)procId)
250 PostMessage(hwnd, WM_CLOSE, 0, 0);
257 SystemExec::make_envp() {
258 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
262 SystemExec::make_wargs(char **a) {
263 std::string wa = cmd;
264 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
265 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
267 while (tmp && *tmp) {
273 w_args = strdup(wa.c_str());
277 SystemExec::make_argp(std::string args) {
278 std::string wa = cmd;
279 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
280 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
283 w_args = strdup(wa.c_str());
287 SystemExec::terminate ()
289 ::pthread_mutex_lock(&write_lock);
292 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
293 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
296 TerminateProcess(pid->hProcess, 0xf291);
298 CloseHandle(pid->hThread);
299 CloseHandle(pid->hProcess);
300 destroy_pipe(stdinP);
301 destroy_pipe(stdoutP);
302 destroy_pipe(stderrP);
306 ::pthread_mutex_unlock(&write_lock);
310 SystemExec::wait (int options)
312 while (is_running()) {
313 WaitForSingleObject(pid->hProcess, INFINITE);
320 SystemExec::is_running ()
322 return pid?true:false;
326 SystemExec::start (int stderr_mode)
328 char* working_dir = 0;
330 if (pid) { return 0; }
332 pid = new PROCESS_INFORMATION;
333 memset(pid, 0, sizeof(PROCESS_INFORMATION));
335 create_pipe(stdinP, true);
336 create_pipe(stdoutP, false);
338 if (stderr_mode == 2) {
339 /* merge stout & stderr */
340 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
341 } else if (stderr_mode == 1) {
342 //TODO read/flush this pipe or close it...
343 create_pipe(stderrP, false);
345 //TODO: keep stderr of this process mode.
348 bool success = false;
349 STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
350 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
351 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
353 STARTF_USESTDHANDLES,
355 stdinP[0], stdoutP[1], stderrP[1]
358 success = CreateProcess(0, w_args,
359 0, 0, /* bInheritHandles = */ TRUE,
360 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
365 if (stdinP[0] != INVALID_HANDLE_VALUE) {
366 CloseHandle(stdinP[0]);
367 stdinP[0] = INVALID_HANDLE_VALUE;
369 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
370 CloseHandle(stdoutP[1]);
371 stdoutP[1] = INVALID_HANDLE_VALUE;
373 if (stderrP[1] != INVALID_HANDLE_VALUE) {
374 CloseHandle(stderrP[1]);
375 stderrP[1] = INVALID_HANDLE_VALUE;
379 CloseHandle(pid->hThread);
380 CloseHandle(pid->hProcess);
381 destroy_pipe(stdinP);
382 destroy_pipe(stdoutP);
383 destroy_pipe(stderrP);
389 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
401 SystemExec::output_interposer()
405 #if 0 // untested code to set up nonblocking
407 ioctlsocket(stdoutP[0], FIONBIO, &l);
410 #if 0 // for non-blocking pipes..
411 DWORD bytesAvail = 0;
412 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
413 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
415 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
416 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) break;
417 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
419 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
421 Terminated();/* EMIT SIGNAL */
425 SystemExec::close_stdin()
427 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
428 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
430 destroy_pipe(stdinP);
434 SystemExec::write_to_stdin(std::string d, size_t len)
439 ::pthread_mutex_lock(&write_lock);
447 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
448 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
452 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
458 ::pthread_mutex_unlock(&write_lock);
463 /* end windows process */
465 /* UNIX/POSIX process */
467 extern char **environ;
469 SystemExec::make_envp() {
471 envp = (char **) calloc(1, sizeof(char*));
472 /* copy current environment */
473 for (i=0;environ[i];++i) {
474 envp[i] = strdup(environ[i]);
475 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
481 SystemExec::make_argp(std::string args) {
486 char *carg = strdup(args.c_str());
488 argp = (char **) malloc((argn + 1) * sizeof(char *));
489 if (argp == (char **) 0) {
494 argp[0] = strdup(cmd.c_str());
496 /* TODO: quotations and escapes
497 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
499 * It's actually not needed. All relevant invocations specify 'argp' directly.
500 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
501 * nor arguments with white-space.
503 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
506 argp[argn++] = strdup(cp1);
508 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
512 argp[argn++] = strdup(cp1);
513 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
515 argp[argn] = (char *) 0;
522 SystemExec::terminate ()
524 ::pthread_mutex_lock(&write_lock);
526 /* close stdin in an attempt to get the child to exit cleanly.
537 /* if pid is non-zero, the child task is still executing (i.e. it did
538 * not exit in response to stdin being closed). try to kill it.
542 ::kill(pid, SIGTERM);
548 /* if pid is non-zero, the child task is STILL executing after being
549 * sent SIGTERM. Act tough ... send SIGKILL
553 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
554 ::kill(pid, SIGKILL);
558 if (thread_active) pthread_join(thread_id_tt, NULL);
559 thread_active = false;
560 ::pthread_mutex_unlock(&write_lock);
564 SystemExec::wait (int options)
569 if (pid==0) return -1;
571 ret = waitpid (pid, &status, options);
574 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
579 if (errno == ECHILD) {
580 /* no currently running children, reset pid */
583 } /* else the process is still running */
589 SystemExec::is_running ()
592 if (pid==0) return false;
593 if (::waitpid(pid, &status, WNOHANG)==0) return true;
598 SystemExec::start (int stderr_mode)
601 return 0; // mmh what to return here?
605 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
606 /* Something unexpected went wrong creating a pipe. */
620 /* check if execve was successful. */
624 ssize_t n = ::read(pok[0], &buf, 1 );
626 /* child process returned from execve */
635 } else if ( n==-1 ) {
636 if ( errno==EAGAIN || errno==EINTR )
642 /* child started successfully */
645 /* use fork for output-interposer
646 * it will run in a separated process
648 /* catch stdout thread */
656 /* 2nd child process - catch stdout */
665 #else /* use pthread */
668 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
677 return 0; /* all systems go - return to main */
680 /* child process - exec external process */
682 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
685 if (pin[0] != STDIN_FILENO) {
686 ::dup2(pin[0], STDIN_FILENO);
690 if (pout[1] != STDOUT_FILENO) {
691 ::dup2(pout[1], STDOUT_FILENO);
694 if (stderr_mode == 2) {
695 /* merge STDERR into output */
696 if (pout[1] != STDERR_FILENO) {
697 ::dup2(pout[1], STDERR_FILENO);
699 } else if (stderr_mode == 1) {
701 ::close(STDERR_FILENO);
706 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
715 /* chdir to executable dir */
717 directory = strdup(cmd.c_str());
718 if (strrchr(directory, '/') != (char *) 0) {
725 sigset(SIGPIPE, SIG_DFL);
727 signal(SIGPIPE, SIG_DFL);
730 int good_fds[1] = { -1 };
731 close_allv(good_fds);
733 ::execve(argp[0], argp, envp);
734 /* if we reach here something went wrong.. */
736 (void) ::write(pok[1], &buf, 1 );
743 SystemExec::output_interposer()
750 ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
752 for (;fcntl(rfd, F_GETFL)!=-1;) {
753 r = read(rfd, buf, sizeof(buf));
754 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
762 std::string rv = std::string(buf,r); // TODO: check allocation strategy
763 ReadStdout(rv, r);/* EMIT SIGNAL */
765 Terminated();/* EMIT SIGNAL */
769 SystemExec::close_stdin()
771 if (pin[1]<0) return;
779 SystemExec::write_to_stdin(std::string d, size_t len)
784 ::pthread_mutex_lock(&write_lock);
793 r=::write(pin[1], data+c, len-c);
794 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
798 if ((size_t) r != (len-c)) {
799 ::pthread_mutex_unlock(&write_lock);
807 ::pthread_mutex_unlock(&write_lock);
811 #endif // end UNIX process