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.
34 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <sys/ioctl.h>
39 #include <sys/resource.h>
43 #include "system_exec.h"
46 void * interposer_thread (void *arg);
48 static void close_fd (int& fd) { if (fd >= 0) ::close (fd); fd = -1; }
52 * This function was part of libasyncns.
54 * Copyright 2005-2008 Lennart Poettering
56 static int close_allv(const int except_fds[]) {
66 if ((d = opendir("/proc/self/fd"))) {
69 while ((de = readdir(d))) {
75 if (de->d_name[0] == '.')
79 l = strtol(de->d_name, &e, 10);
80 if (errno != 0 || !e || *e) {
101 for (i = 0; except_fds[i] >= 0; i++)
102 if (except_fds[i] == fd) {
126 if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
129 for (fd = 0; fd < (int) rl.rlim_max; fd++) {
135 for (i = 0; except_fds[i] >= 0; i++)
136 if (except_fds[i] == fd)
139 if (close(fd) < 0 && errno != EBADF)
145 #endif /* not on windows */
148 SystemExec::SystemExec (std::string c, std::string a)
151 pthread_mutex_init(&write_lock, NULL);
159 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
160 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
161 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
167 SystemExec::SystemExec (std::string c, char **a)
170 pthread_mutex_init(&write_lock, NULL);
177 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
178 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
179 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
185 SystemExec::~SystemExec ()
189 for (int i=0;envp[i];++i) {
195 for (int i=0;argp[i];++i) {
201 if (w_args) free(w_args);
203 pthread_mutex_destroy(&write_lock);
207 interposer_thread (void *arg) {
208 SystemExec *sex = static_cast<SystemExec *>(arg);
209 sex->output_interposer();
214 #ifdef __WIN32__ /* Windows Process */
216 /* HELPER FUNCTIONS */
218 static void create_pipe (HANDLE *pipe, bool in) {
219 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
222 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
223 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
225 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
226 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
228 CloseHandle(tmpHandle);
231 static void destroy_pipe (HANDLE pipe[2]) {
232 if (pipe[0] != INVALID_HANDLE_VALUE) {
233 CloseHandle(pipe[0]);
234 pipe[0] = INVALID_HANDLE_VALUE;
236 if (pipe[1] != INVALID_HANDLE_VALUE) {
237 CloseHandle(pipe[1]);
238 pipe[1] = INVALID_HANDLE_VALUE;
242 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
244 DWORD currentProcId = 0;
245 GetWindowThreadProcessId(hwnd, ¤tProcId);
246 if (currentProcId == (DWORD)procId)
247 PostMessage(hwnd, WM_CLOSE, 0, 0);
254 SystemExec::make_envp() {
255 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
259 SystemExec::make_wargs(char **a) {
260 std::string wa = cmd;
261 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
262 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
264 while (tmp && *tmp) {
270 w_args = strdup(wa.c_str());
274 SystemExec::make_argp(std::string args) {
275 std::string wa = cmd;
276 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
277 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
280 w_args = strdup(wa.c_str());
284 SystemExec::terminate ()
286 ::pthread_mutex_lock(&write_lock);
289 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
290 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
293 TerminateProcess(pid->hProcess, 0xf291);
295 CloseHandle(pid->hThread);
296 CloseHandle(pid->hProcess);
297 destroy_pipe(stdinP);
298 destroy_pipe(stdoutP);
299 destroy_pipe(stderrP);
303 ::pthread_mutex_unlock(&write_lock);
307 SystemExec::wait (int options)
309 while (is_running()) {
310 WaitForSingleObject(pid->hProcess, INFINITE);
317 SystemExec::is_running ()
319 return pid?true:false;
323 SystemExec::start (int stderr_mode)
325 char* working_dir = 0;
327 if (pid) { return 0; }
329 pid = new PROCESS_INFORMATION;
330 memset(pid, 0, sizeof(PROCESS_INFORMATION));
332 create_pipe(stdinP, true);
333 create_pipe(stdoutP, false);
335 if (stderr_mode == 2) {
336 /* merge stout & stderr */
337 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
338 } else if (stderr_mode == 1) {
339 //TODO read/flush this pipe or close it...
340 create_pipe(stderrP, false);
342 //TODO: keep stderr of this process mode.
345 bool success = false;
346 STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
347 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
348 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
350 STARTF_USESTDHANDLES,
352 stdinP[0], stdoutP[1], stderrP[1]
355 success = CreateProcess(0, w_args,
356 0, 0, /* bInheritHandles = */ TRUE,
357 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
362 if (stdinP[0] != INVALID_HANDLE_VALUE) {
363 CloseHandle(stdinP[0]);
364 stdinP[0] = INVALID_HANDLE_VALUE;
366 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
367 CloseHandle(stdoutP[1]);
368 stdoutP[1] = INVALID_HANDLE_VALUE;
370 if (stderrP[1] != INVALID_HANDLE_VALUE) {
371 CloseHandle(stderrP[1]);
372 stderrP[1] = INVALID_HANDLE_VALUE;
376 CloseHandle(pid->hThread);
377 CloseHandle(pid->hProcess);
378 destroy_pipe(stdinP);
379 destroy_pipe(stdoutP);
380 destroy_pipe(stderrP);
386 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
398 SystemExec::output_interposer()
402 #if 0 // untested code to set up nonblocking
404 ioctlsocket(stdoutP[0], FIONBIO, &l);
407 #if 0 // for non-blocking pipes..
408 DWORD bytesAvail = 0;
409 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
410 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
412 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
413 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) break;
414 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
416 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
418 Terminated();/* EMIT SIGNAL */
422 SystemExec::close_stdin()
424 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
425 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
427 destroy_pipe(stdinP);
431 SystemExec::write_to_stdin(std::string d, size_t len)
436 ::pthread_mutex_lock(&write_lock);
444 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
445 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
449 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
455 ::pthread_mutex_unlock(&write_lock);
460 /* end windows process */
462 /* UNIX/POSIX process */
464 extern char **environ;
466 SystemExec::make_envp() {
468 envp = (char **) calloc(1, sizeof(char*));
469 /* copy current environment */
470 for (i=0;environ[i];++i) {
471 envp[i] = strdup(environ[i]);
472 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
478 SystemExec::make_argp(std::string args) {
483 char *carg = strdup(args.c_str());
485 argp = (char **) malloc((argn + 1) * sizeof(char *));
486 if (argp == (char **) 0) {
491 argp[0] = strdup(cmd.c_str());
493 /* TODO: quotations and escapes
494 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
496 * It's actually not needed. All relevant invocations specify 'argp' directly.
497 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
498 * nor arguments with white-space.
500 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
503 argp[argn++] = strdup(cp1);
505 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
509 argp[argn++] = strdup(cp1);
510 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
512 argp[argn] = (char *) 0;
519 SystemExec::terminate ()
521 ::pthread_mutex_lock(&write_lock);
523 /* close stdin in an attempt to get the child to exit cleanly.
534 /* if pid is non-zero, the child task is still executing (i.e. it did
535 * not exit in response to stdin being closed). try to kill it.
539 ::kill(pid, SIGTERM);
545 /* if pid is non-zero, the child task is STILL executing after being
546 * sent SIGTERM. Act tough ... send SIGKILL
550 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
551 ::kill(pid, SIGKILL);
555 if (thread_active) pthread_join(thread_id_tt, NULL);
556 thread_active = false;
557 ::pthread_mutex_unlock(&write_lock);
561 SystemExec::wait (int options)
566 if (pid==0) return -1;
568 ret = waitpid (pid, &status, options);
571 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
576 if (errno == ECHILD) {
577 /* no currently running children, reset pid */
580 } /* else the process is still running */
586 SystemExec::is_running ()
589 if (pid==0) return false;
590 if (::waitpid(pid, &status, WNOHANG)==0) return true;
595 SystemExec::start (int stderr_mode)
598 return 0; // mmh what to return here?
602 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
603 /* Something unexpected went wrong creating a pipe. */
617 /* check if execve was successful. */
621 ssize_t n = ::read(pok[0], &buf, 1 );
623 /* child process returned from execve */
632 } else if ( n==-1 ) {
633 if ( errno==EAGAIN || errno==EINTR )
639 /* child started successfully */
642 /* use fork for output-interposer
643 * it will run in a separated process
645 /* catch stdout thread */
653 /* 2nd child process - catch stdout */
662 #else /* use pthread */
665 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
674 return 0; /* all systems go - return to main */
677 /* child process - exec external process */
679 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
682 if (pin[0] != STDIN_FILENO) {
683 ::dup2(pin[0], STDIN_FILENO);
687 if (pout[1] != STDOUT_FILENO) {
688 ::dup2(pout[1], STDOUT_FILENO);
691 if (stderr_mode == 2) {
692 /* merge STDERR into output */
693 if (pout[1] != STDERR_FILENO) {
694 ::dup2(pout[1], STDERR_FILENO);
696 } else if (stderr_mode == 1) {
698 ::close(STDERR_FILENO);
703 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
712 /* chdir to executable dir */
714 directory = strdup(cmd.c_str());
715 if (strrchr(directory, '/') != (char *) 0) {
722 sigset(SIGPIPE, SIG_DFL);
724 signal(SIGPIPE, SIG_DFL);
727 int good_fds[1] = { -1 };
728 close_allv(good_fds);
730 ::execve(argp[0], argp, envp);
731 /* if we reach here something went wrong.. */
733 (void) ::write(pok[1], &buf, 1 );
740 SystemExec::output_interposer()
747 ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
749 for (;fcntl(rfd, F_GETFL)!=-1;) {
750 r = read(rfd, buf, sizeof(buf));
751 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
759 std::string rv = std::string(buf,r); // TODO: check allocation strategy
760 ReadStdout(rv, r);/* EMIT SIGNAL */
762 Terminated();/* EMIT SIGNAL */
766 SystemExec::close_stdin()
768 if (pin[1]<0) return;
776 SystemExec::write_to_stdin(std::string d, size_t len)
781 ::pthread_mutex_lock(&write_lock);
790 r=::write(pin[1], data+c, len-c);
791 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
795 if ((size_t) r != (len-c)) {
796 ::pthread_mutex_unlock(&write_lock);
804 ::pthread_mutex_unlock(&write_lock);
808 #endif // end UNIX process