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.
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 "pbd/system_exec.h"
51 static void * interposer_thread (void *arg);
52 static void close_fd (int& fd) { if (fd >= 0) ::close (fd); fd = -1; }
54 #ifndef PLATFORM_WINDOWS
56 * This function was part of libasyncns.
58 * Copyright 2005-2008 Lennart Poettering
60 static int close_allv(const int except_fds[]) {
70 if ((d = opendir("/proc/self/fd"))) {
73 while ((de = readdir(d))) {
79 if (de->d_name[0] == '.')
83 l = strtol(de->d_name, &e, 10);
84 if (errno != 0 || !e || *e) {
105 for (i = 0; except_fds[i] >= 0; i++)
106 if (except_fds[i] == fd) {
130 if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
133 for (fd = 0; fd < (int) rl.rlim_max; fd++) {
139 for (i = 0; except_fds[i] >= 0; i++)
140 if (except_fds[i] == fd)
143 if (close(fd) < 0 && errno != EBADF)
149 #endif /* not on windows */
152 SystemExec::SystemExec (std::string c, std::string a)
155 pthread_mutex_init(&write_lock, NULL);
162 #ifdef PLATFORM_WINDOWS
163 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
164 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
165 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
171 SystemExec::SystemExec (std::string c, char **a)
174 pthread_mutex_init(&write_lock, NULL);
180 #ifdef PLATFORM_WINDOWS
181 stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
182 stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
183 stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
189 SystemExec::~SystemExec ()
193 for (int i=0;envp[i];++i) {
199 for (int i=0;argp[i];++i) {
204 #ifdef PLATFORM_WINDOWS
205 if (w_args) free(w_args);
207 pthread_mutex_destroy(&write_lock);
211 interposer_thread (void *arg) {
212 SystemExec *sex = static_cast<SystemExec *>(arg);
213 sex->output_interposer();
218 #ifdef PLATFORM_WINDOWS /* Windows Process */
220 /* HELPER FUNCTIONS */
222 static void create_pipe (HANDLE *pipe, bool in) {
223 SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
226 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
227 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
229 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
230 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
232 CloseHandle(tmpHandle);
235 static void destroy_pipe (HANDLE pipe[2]) {
236 if (pipe[0] != INVALID_HANDLE_VALUE) {
237 CloseHandle(pipe[0]);
238 pipe[0] = INVALID_HANDLE_VALUE;
240 if (pipe[1] != INVALID_HANDLE_VALUE) {
241 CloseHandle(pipe[1]);
242 pipe[1] = INVALID_HANDLE_VALUE;
246 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
248 DWORD currentProcId = 0;
249 GetWindowThreadProcessId(hwnd, ¤tProcId);
250 if (currentProcId == (DWORD)procId)
251 PostMessage(hwnd, WM_CLOSE, 0, 0);
258 SystemExec::make_envp() {
259 ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
263 SystemExec::make_wargs(char **a) {
264 std::string wa = cmd;
265 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
266 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
268 while (tmp && *tmp) {
274 w_args = strdup(wa.c_str());
278 SystemExec::make_argp(std::string args) {
279 std::string wa = cmd;
280 if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
281 std::replace(cmd.begin(), cmd.end(), '/', '\\' );
284 w_args = strdup(wa.c_str());
288 SystemExec::terminate ()
290 ::pthread_mutex_lock(&write_lock);
293 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
294 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
297 TerminateProcess(pid->hProcess, 0xf291);
299 CloseHandle(pid->hThread);
300 CloseHandle(pid->hProcess);
301 destroy_pipe(stdinP);
302 destroy_pipe(stdoutP);
303 destroy_pipe(stderrP);
307 ::pthread_mutex_unlock(&write_lock);
311 SystemExec::wait (int options)
313 while (is_running()) {
314 WaitForSingleObject(pid->hProcess, INFINITE);
321 SystemExec::is_running ()
323 return pid?true:false;
327 SystemExec::start (int stderr_mode)
329 char* working_dir = 0;
331 if (pid) { return 0; }
333 pid = new PROCESS_INFORMATION;
334 memset(pid, 0, sizeof(PROCESS_INFORMATION));
336 create_pipe(stdinP, true);
337 create_pipe(stdoutP, false);
339 if (stderr_mode == 2) {
340 /* merge stout & stderr */
341 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
342 } else if (stderr_mode == 1) {
343 //TODO read/flush this pipe or close it...
344 create_pipe(stderrP, false);
346 //TODO: keep stderr of this process mode.
349 bool success = false;
350 STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
351 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
352 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
354 STARTF_USESTDHANDLES,
356 stdinP[0], stdoutP[1], stderrP[1]
359 success = CreateProcess(0, w_args,
360 0, 0, /* bInheritHandles = */ TRUE,
361 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
366 if (stdinP[0] != INVALID_HANDLE_VALUE) {
367 CloseHandle(stdinP[0]);
368 stdinP[0] = INVALID_HANDLE_VALUE;
370 if (stdoutP[1] != INVALID_HANDLE_VALUE) {
371 CloseHandle(stdoutP[1]);
372 stdoutP[1] = INVALID_HANDLE_VALUE;
374 if (stderrP[1] != INVALID_HANDLE_VALUE) {
375 CloseHandle(stderrP[1]);
376 stderrP[1] = INVALID_HANDLE_VALUE;
380 CloseHandle(pid->hThread);
381 CloseHandle(pid->hProcess);
382 destroy_pipe(stdinP);
383 destroy_pipe(stdoutP);
384 destroy_pipe(stderrP);
390 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
402 SystemExec::output_interposer()
406 #if 0 // untested code to set up nonblocking
408 ioctlsocket(stdoutP[0], FIONBIO, &l);
411 #if 0 // for non-blocking pipes..
412 DWORD bytesAvail = 0;
413 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
414 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
416 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
417 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) break;
418 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
420 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
422 Terminated();/* EMIT SIGNAL */
426 SystemExec::close_stdin()
428 if (stdinP[0]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[0]);
429 if (stdinP[1]!= INVALID_HANDLE_VALUE) FlushFileBuffers(stdinP[1]);
431 destroy_pipe(stdinP);
435 SystemExec::write_to_stdin(std::string d, size_t len)
440 ::pthread_mutex_lock(&write_lock);
448 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
449 if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
453 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
459 ::pthread_mutex_unlock(&write_lock);
464 /* end windows process */
466 /* UNIX/POSIX process */
468 extern char **environ;
470 SystemExec::make_envp() {
472 envp = (char **) calloc(1, sizeof(char*));
473 /* copy current environment */
474 for (i=0;environ[i];++i) {
475 envp[i] = strdup(environ[i]);
476 envp = (char **) realloc(envp, (i+2) * sizeof(char*));
482 SystemExec::make_argp(std::string args) {
487 char *carg = strdup(args.c_str());
489 argp = (char **) malloc((argn + 1) * sizeof(char *));
490 if (argp == (char **) 0) {
495 argp[0] = strdup(cmd.c_str());
497 /* TODO: quotations and escapes
498 * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
500 * It's actually not needed. All relevant invocations specify 'argp' directly.
501 * Only 'xjadeo -L -R' uses this function and that uses neither quotations
502 * nor arguments with white-space.
504 for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
507 argp[argn++] = strdup(cp1);
509 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
513 argp[argn++] = strdup(cp1);
514 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
516 argp[argn] = (char *) 0;
523 SystemExec::terminate ()
525 ::pthread_mutex_lock(&write_lock);
527 /* close stdin in an attempt to get the child to exit cleanly.
538 /* if pid is non-zero, the child task is still executing (i.e. it did
539 * not exit in response to stdin being closed). try to kill it.
543 ::kill(pid, SIGTERM);
549 /* if pid is non-zero, the child task is STILL executing after being
550 * sent SIGTERM. Act tough ... send SIGKILL
554 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
555 ::kill(pid, SIGKILL);
559 if (thread_active) pthread_join(thread_id_tt, NULL);
560 thread_active = false;
561 ::pthread_mutex_unlock(&write_lock);
565 SystemExec::wait (int options)
570 if (pid==0) return -1;
572 ret = waitpid (pid, &status, options);
575 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
580 if (errno == ECHILD) {
581 /* no currently running children, reset pid */
584 } /* else the process is still running */
590 SystemExec::is_running ()
593 if (pid==0) return false;
594 if (::waitpid(pid, &status, WNOHANG)==0) return true;
599 SystemExec::start (int stderr_mode)
602 return 0; // mmh what to return here?
606 if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
607 /* Something unexpected went wrong creating a pipe. */
621 /* check if execve was successful. */
625 ssize_t n = ::read(pok[0], &buf, 1 );
627 /* child process returned from execve */
636 } else if ( n==-1 ) {
637 if ( errno==EAGAIN || errno==EINTR )
643 /* child started successfully */
646 /* use fork for output-interposer
647 * it will run in a separated process
649 /* catch stdout thread */
657 /* 2nd child process - catch stdout */
666 #else /* use pthread */
669 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
678 return 0; /* all systems go - return to main */
681 /* child process - exec external process */
683 ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
686 if (pin[0] != STDIN_FILENO) {
687 ::dup2(pin[0], STDIN_FILENO);
691 if (pout[1] != STDOUT_FILENO) {
692 ::dup2(pout[1], STDOUT_FILENO);
695 if (stderr_mode == 2) {
696 /* merge STDERR into output */
697 if (pout[1] != STDERR_FILENO) {
698 ::dup2(pout[1], STDERR_FILENO);
700 } else if (stderr_mode == 1) {
702 ::close(STDERR_FILENO);
707 if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
716 /* chdir to executable dir */
718 directory = strdup(cmd.c_str());
719 if (strrchr(directory, '/') != (char *) 0) {
726 sigset(SIGPIPE, SIG_DFL);
728 signal(SIGPIPE, SIG_DFL);
731 int good_fds[1] = { -1 };
732 close_allv(good_fds);
734 ::execve(argp[0], argp, envp);
735 /* if we reach here something went wrong.. */
737 (void) ::write(pok[1], &buf, 1 );
744 SystemExec::output_interposer()
751 ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
753 for (;fcntl(rfd, F_GETFL)!=-1;) {
754 r = read(rfd, buf, sizeof(buf));
755 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
763 std::string rv = std::string(buf,r); // TODO: check allocation strategy
764 ReadStdout(rv, r);/* EMIT SIGNAL */
766 Terminated();/* EMIT SIGNAL */
770 SystemExec::close_stdin()
772 if (pin[1]<0) return;
780 SystemExec::write_to_stdin(std::string d, size_t len)
785 ::pthread_mutex_lock(&write_lock);
794 r=::write(pin[1], data+c, len-c);
795 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
799 if ((size_t) r != (len-c)) {
800 ::pthread_mutex_unlock(&write_lock);
808 ::pthread_mutex_unlock(&write_lock);
812 #endif // end UNIX process