1 /* filter.c: filter framework functions
3 * Copyright (C) 2006-2014 cgit Development Team <cgit@lists.zx2c4.com>
5 * Licensed under GNU General Public License v2
6 * (see COPYING for full license text)
10 #include <sys/types.h>
16 int cgit_open_filter(struct cgit_filter *filter, ...)
22 for (i = 0; i < filter->extra_args; i++)
23 filter->argv[i+1] = va_arg(ap, char *);
26 filter->old_stdout = chk_positive(dup(STDOUT_FILENO),
27 "Unable to duplicate STDOUT");
28 chk_zero(pipe(filter->pipe_fh), "Unable to create pipe to subprocess");
29 filter->pid = chk_non_negative(fork(), "Unable to create subprocess");
30 if (filter->pid == 0) {
31 close(filter->pipe_fh[1]);
32 chk_non_negative(dup2(filter->pipe_fh[0], STDIN_FILENO),
33 "Unable to use pipe as STDIN");
34 execvp(filter->cmd, filter->argv);
35 die_errno("Unable to exec subprocess %s", filter->cmd);
37 close(filter->pipe_fh[0]);
38 chk_non_negative(dup2(filter->pipe_fh[1], STDOUT_FILENO),
39 "Unable to use pipe as STDOUT");
40 close(filter->pipe_fh[1]);
45 int cgit_close_filter(struct cgit_filter *filter)
49 chk_non_negative(dup2(filter->old_stdout, STDOUT_FILENO),
50 "Unable to restore STDOUT");
51 close(filter->old_stdout);
54 waitpid(filter->pid, &exit_status, 0);
55 if (WIFEXITED(exit_status) && !WEXITSTATUS(exit_status))
57 die("Subprocess %s exited abnormally", filter->cmd);
60 for (i = 0; i < filter->extra_args; i++)
61 filter->argv[i+1] = NULL;
66 struct cgit_filter *cgit_new_filter(const char *cmd, filter_type filtertype)
68 struct cgit_filter *f;
74 f = xmalloc(sizeof(struct cgit_filter));
75 memset(f, 0, sizeof(struct cgit_filter));
89 f->cmd = xstrdup(cmd);
90 args_size = (2 + f->extra_args) * sizeof(char *);
91 f->argv = xmalloc(args_size);
92 memset(f->argv, 0, args_size);