From mboxrd@z Thu Jan 1 00:00:00 1970 From: Jason at zx2c4.com (Jason A. Donenfeld) Date: Sat, 14 Oct 2017 16:17:48 +0200 Subject: [PATCH 2/4] filter: wire up exec_filter to enable function In-Reply-To: <20171014141750.14013-1-Jason@zx2c4.com> References: <20171014141750.14013-1-Jason@zx2c4.com> Message-ID: <20171014141750.14013-3-Jason@zx2c4.com> We also move pipe_fh to be local, since it's not needed any place else. Signed-off-by: Jason A. Donenfeld --- cgit.h | 1 + filter.c | 27 +++++++++++++++++++++------ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/cgit.h b/cgit.h index 8da69e7..f9949a7 100644 --- a/cgit.h +++ b/cgit.h @@ -72,6 +72,7 @@ struct cgit_exec_filter { char *cmd; char **argv; int old_stdout; + int new_stdout; int pid; }; diff --git a/filter.c b/filter.c index aa0027a..4deb4de 100644 --- a/filter.c +++ b/filter.c @@ -60,9 +60,8 @@ static int open_exec_filter(struct cgit_filter *base, va_list ap) die_errno("Unable to exec subprocess %s", filter->cmd); } close(pipe_fh[0]); - chk_non_negative(dup2(pipe_fh[1], STDOUT_FILENO), - "Unable to use pipe as STDOUT"); - close(pipe_fh[1]); + filter->new_stdout = pipe_fh[1]; + chk_non_negative(dup2(filter->new_stdout, STDOUT_FILENO), "Unable to assign new fd to STDOUT"); return 0; } @@ -71,9 +70,10 @@ static int close_exec_filter(struct cgit_filter *base) struct cgit_exec_filter *filter = (struct cgit_exec_filter *)base; int i, exit_status = 0; - chk_non_negative(dup2(filter->old_stdout, STDOUT_FILENO), - "Unable to restore STDOUT"); + chk_non_negative(dup2(filter->old_stdout, STDOUT_FILENO), "Unable to assign old fd to STDOUT"); close(filter->old_stdout); + close(filter->new_stdout); + if (filter->pid < 0) goto done; waitpid(filter->pid, &exit_status, 0); @@ -82,10 +82,24 @@ static int close_exec_filter(struct cgit_filter *base) die("Subprocess %s exited abnormally", filter->cmd); done: + close(filter->old_stdout); + close(filter->new_stdout); for (i = 0; i < filter->base.argument_count; i++) filter->argv[i + 1] = NULL; - return WEXITSTATUS(exit_status); + return WIFEXITED(exit_status); +} +static int enable_exec_filter(struct cgit_filter *base, bool on) +{ + struct cgit_exec_filter *filter = (struct cgit_exec_filter *)base; + int ret; + + if (on) + ret = dup2(filter->new_stdout, STDOUT_FILENO); + else + ret = dup2(filter->old_stdout, STDOUT_FILENO); + chk_non_negative(ret, "Unable to assign fd to STDOUT"); + return 0; } static void fprintf_exec_filter(struct cgit_filter *base, FILE *f, const char *prefix) @@ -128,6 +142,7 @@ void cgit_exec_filter_init(struct cgit_exec_filter *filter, char *cmd, char **ar memset(filter, 0, sizeof(*filter)); filter->base.open = open_exec_filter; filter->base.close = close_exec_filter; + filter->base.enable = enable_exec_filter; filter->base.fprintf = fprintf_exec_filter; filter->base.cleanup = cleanup_exec_filter; filter->cmd = cmd; -- 2.14.2