2 Copyright (C) 2010 Paul Davis
3 Author: Robin Gareus <robin@gareus.org>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
30 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <sys/ioctl.h>
36 #include "system_exec.h"
39 void * interposer_thread (void *arg);
41 static void close_fd (int* fd) { if (!fd) return; if (*fd >= 0) ::close (*fd); *fd = -1; }
43 SystemExec::SystemExec (std::string c, std::string a)
46 pthread_mutex_init(&write_lock, NULL);
54 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
55 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
56 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
62 SystemExec::SystemExec (std::string c, char **a)
65 pthread_mutex_init(&write_lock, NULL);
72 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
73 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
74 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
80 SystemExec::~SystemExec ()
84 for (int i=0;envp[i];++i) {
90 for (int i=0;argp[i];++i) {
96 if (w_args) free(w_args);
98 pthread_mutex_destroy(&write_lock);
102 interposer_thread (void *arg) {
103 SystemExec *sex = static_cast<SystemExec *>(arg);
104 sex->output_interposer();
109 #ifdef __WIN32__ /* Windows Process */
111 /* HELPER FUNCTIONS */
113 static void create_pipe (HANDLE *pipe, bool in) {
114 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
117 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
118 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
120 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
121 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
123 CloseHandle(tmpHandle);
126 static void destroy_pipe (HANDLE pipe[2]) {
127 if (pipe[0] != INVALID_HANDLE_VALUE) {
128 CloseHandle(pipe[0]);
129 pipe[0] = INVALID_HANDLE_VALUE;
131 if (pipe[1] != INVALID_HANDLE_VALUE) {
132 CloseHandle(pipe[1]);
133 pipe[1] = INVALID_HANDLE_VALUE;
137 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
139 DWORD currentProcId = 0;
140 GetWindowThreadProcessId(hwnd, ¤tProcId);
141 if (currentProcId == (DWORD)procId)
142 PostMessage(hwnd, WM_CLOSE, 0, 0);
149 SystemExec::make_envp() {
150 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
154 SystemExec::make_wargs(char **a) {
155 std::string wa = cmd;
156 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
157 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
159 while (tmp && *tmp) {
165 w_args = strdup(wa.c_str());
169 SystemExec::make_argp(std::string args) {
170 std::string wa = cmd;
171 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
172 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
175 w_args = strdup(wa.c_str());
179 SystemExec::terminate ()
181 ::pthread_mutex_lock(&write_lock);
184 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
185 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
188 TerminateProcess(pid->hProcess, 0xf291);
190 CloseHandle(pid->hThread);
191 CloseHandle(pid->hProcess);
192 destroy_pipe(stdinP);
193 destroy_pipe(stdoutP);
194 destroy_pipe(stderrP);
198 ::pthread_mutex_unlock(&write_lock);
202 SystemExec::wait (int options)
204 while (is_running()) {
205 WaitForSingleObject(pid->hProcess, INFINITE);
212 SystemExec::is_running ()
214 return pid?true:false;
218 SystemExec::start (int stderr_mode)
220 char* working_dir = 0;
222 if (pid) { return 0; }
224 pid = new PROCESS_INFORMATION;
225 memset(pid, 0, sizeof(PROCESS_INFORMATION));
227 create_pipe(stdinP, true);
228 create_pipe(stdoutP, false);
230 if (stderr_mode == 2) {
231 /* merge stout & stderr */
232 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
233 } else if (stderr_mode == 1) {
234 //TODO read/flush this pipe or close it...
235 create_pipe(stderrP, false);
237 //TODO: keep stderr of this process mode.
240 bool success = false;
241 STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
242 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
243 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
245 STARTF_USESTDHANDLES,
247 stdinP[0], stdoutP[1], stderrP[1]
250 success = CreateProcess(0, w_args,
251 0, 0, /* bInheritHandles = */ TRUE,
252 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
257 if (stdinP[0] != INVALID_HANDLE_VALUE) {
258 CloseHandle(stdinP[0]);
259 stdinP[0] = INVALID_HANDLE_VALUE;
261 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
262 CloseHandle(stdoutP[1]);
263 stdoutP[1] = INVALID_HANDLE_VALUE;
265 if (stderrP[1] != INVALID_HANDLE_VALUE) {
266 CloseHandle(stderrP[1]);
267 stderrP[1] = INVALID_HANDLE_VALUE;
271 CloseHandle(pid->hThread);
272 CloseHandle(pid->hProcess);
273 destroy_pipe(stdinP);
274 destroy_pipe(stdoutP);
275 destroy_pipe(stderrP);
281 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
293 SystemExec::output_interposer()
297 #if 0 // untested code to set up nonblocking
299 ioctlsocket(stdoutP[0], FIONBIO, &l);
302 #if 0 // for non-blocking pipes..
303 DWORD bytesAvail = 0;
304 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
305 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
307 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
308 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) break;
309 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
311 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
313 Terminated();/* EMIT SIGNAL */
317 SystemExec::close_stdin()
319 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
320 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
322 destroy_pipe(stdinP);
326 SystemExec::write_to_stdin(std::string d, size_t len)
331 ::pthread_mutex_lock(&write_lock);
339 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
340 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
344 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
350 ::pthread_mutex_unlock(&write_lock);
355 /* end windows process */
357 /* UNIX/POSIX process */
359 extern char **environ;
361 SystemExec::make_envp() {
363 envp = (char **) calloc(1, sizeof(char*));
364 /* copy current environment */
365 for (i=0;environ[i];++i) {
366 envp[i] = strdup(environ[i]);
367 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
373 SystemExec::make_argp(std::string args) {
378 char *carg = strdup(args.c_str());
380 argp = (char **) malloc((argn + 1) * sizeof(char *));
381 if (argp == (char **) 0) {
386 argp[0] = strdup(cmd.c_str());
388 /* TODO: quotations and escapes
389 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
391 * It's actually not needed. All relevant invocations specify 'argp' directly.
392 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
393 * nor arguments with white-space.
395 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
398 argp[argn++] = strdup(cp1);
400 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
404 argp[argn++] = strdup(cp1);
405 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
407 argp[argn] = (char *) 0;
414 SystemExec::terminate ()
416 ::pthread_mutex_lock(&write_lock);
425 ::kill(pid, SIGTERM);
431 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
432 ::kill(pid, SIGKILL);
436 if (thread_active) pthread_join(thread_id_tt, NULL);
437 thread_active = false;
438 ::pthread_mutex_unlock(&write_lock);
442 SystemExec::wait (int options)
445 if (pid==0) return -1;
446 if (pid==::waitpid(pid, &status, options)) {
449 if (errno == ECHILD) {
456 SystemExec::is_running ()
459 if (pid==0) return false;
460 if (::waitpid(pid, &status, WNOHANG)==0) return true;
465 SystemExec::start (int stderr_mode)
468 return 0; // mmh what to return here?
472 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
473 /* Something unexpected went wrong creating a pipe. */
487 /* check if execve was successful. */
491 ssize_t n = ::read(pok[0], &buf, 1 );
493 /* child process returned from execve */
502 } else if ( n==-1 ) {
503 if ( errno==EAGAIN || errno==EINTR )
509 /* child started successfully */
512 /* use fork for output-interposer
513 * it will run in a separated process
515 /* catch stdout thread */
523 /* 2nd child process - catch stdout */
532 #else /* use pthread */
535 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
544 return 0; /* all systems go - return to main */
547 /* child process - exec external process */
549 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
552 if (pin[0] != STDIN_FILENO) {
553 ::dup2(pin[0], STDIN_FILENO);
557 if (pout[1] != STDOUT_FILENO) {
558 ::dup2(pout[1], STDOUT_FILENO);
561 if (stderr_mode == 2) {
562 /* merge STDERR into output */
563 if (pout[1] != STDERR_FILENO) {
564 ::dup2(pout[1], STDERR_FILENO);
566 } else if (stderr_mode == 1) {
568 ::close(STDERR_FILENO);
573 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
582 /* chdir to executable dir */
584 directory = strdup(cmd.c_str());
585 if (strrchr(directory, '/') != (char *) 0) {
592 sigset(SIGPIPE, SIG_DFL);
594 signal(SIGPIPE, SIG_DFL);
597 ::execve(argp[0], argp, envp);
598 /* if we reach here something went wrong.. */
600 (void) ::write(pok[1], &buf, 1 );
607 SystemExec::output_interposer()
614 ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
616 for (;fcntl(rfd, F_GETFL)!=-1;) {
617 r = read(rfd, buf, sizeof(buf));
618 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
626 std::string rv = std::string(buf,r); // TODO: check allocation strategy
627 ReadStdout(rv, r);/* EMIT SIGNAL */
629 Terminated();/* EMIT SIGNAL */
633 SystemExec::close_stdin()
635 if (pin[1]<0) return;
643 SystemExec::write_to_stdin(std::string d, size_t len)
647 ::pthread_mutex_lock(&write_lock);
656 r=::write(pin[1], data+c, len-c);
657 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
662 ::pthread_mutex_unlock(&write_lock);
670 ::pthread_mutex_unlock(&write_lock);
674 #endif // end UNIX process