diff options
Diffstat (limited to 'plugins/runcmd.c')
-rw-r--r-- | plugins/runcmd.c | 339 |
1 files changed, 339 insertions, 0 deletions
diff --git a/plugins/runcmd.c b/plugins/runcmd.c new file mode 100644 index 0000000..14300ee --- /dev/null +++ b/plugins/runcmd.c | |||
@@ -0,0 +1,339 @@ | |||
1 | /* | ||
2 | * $Id$ | ||
3 | * | ||
4 | * A simple interface to executing programs from other programs, using an | ||
5 | * optimized and safe popen()-like implementation. It is considered safe | ||
6 | * in that no shell needs to be spawned and the environment passed to the | ||
7 | * execve()'d program is essentially empty. | ||
8 | * | ||
9 | * | ||
10 | * The code in this file is a derivative of popen.c which in turn was taken | ||
11 | * from "Advanced Programming for the Unix Environment" by W. Richard Stevens. | ||
12 | * | ||
13 | * Care has been taken to make sure the functions are async-safe. The one | ||
14 | * function which isn't is np_runcmd_init() which it doesn't make sense to | ||
15 | * call twice anyway, so the api as a whole should be considered async-safe. | ||
16 | * | ||
17 | */ | ||
18 | |||
19 | /** includes **/ | ||
20 | #include "runcmd.h" | ||
21 | #ifdef HAVE_SYS_WAIT_H | ||
22 | # include <sys/wait.h> | ||
23 | #endif | ||
24 | |||
25 | /** macros **/ | ||
26 | #ifndef WEXITSTATUS | ||
27 | # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8) | ||
28 | #endif | ||
29 | |||
30 | #ifndef WIFEXITED | ||
31 | # define WIFEXITED(stat_val) (((stat_val) & 255) == 0) | ||
32 | #endif | ||
33 | |||
34 | /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */ | ||
35 | #if defined(SIG_IGN) && !defined(SIG_ERR) | ||
36 | # define SIG_ERR ((Sigfunc *)-1) | ||
37 | #endif | ||
38 | |||
39 | /* This variable must be global, since there's no way the caller | ||
40 | * can forcibly slay a dead or ungainly running program otherwise. | ||
41 | * Multithreading apps and plugins can initialize it (via NP_RUNCMD_INIT) | ||
42 | * in an async safe manner PRIOR to calling np_runcmd() for the first time. | ||
43 | * | ||
44 | * The check for initialized values is atomic and can | ||
45 | * occur in any number of threads simultaneously. */ | ||
46 | static pid_t *np_pids = NULL; | ||
47 | |||
48 | /* If OPEN_MAX isn't defined, we try the sysconf syscall first. | ||
49 | * If that fails, we fall back to an educated guess which is accurate | ||
50 | * on Linux and some other systems. There's no guarantee that our guess is | ||
51 | * adequate and the program will die with SIGSEGV if it isn't and the | ||
52 | * upper boundary is breached. */ | ||
53 | #ifdef OPEN_MAX | ||
54 | # define maxfd OPEN_MAX | ||
55 | #else | ||
56 | # ifndef _SC_OPEN_MAX /* sysconf macro unavailable, so guess */ | ||
57 | # define maxfd 256 | ||
58 | # else | ||
59 | static int maxfd = 0; | ||
60 | # endif /* _SC_OPEN_MAX */ | ||
61 | #endif /* OPEN_MAX */ | ||
62 | |||
63 | |||
64 | /** prototypes **/ | ||
65 | static int np_runcmd_open(const char *, int *, int *) | ||
66 | __attribute__((__nonnull__(1, 2, 3))); | ||
67 | |||
68 | static int np_fetch_output(int, output *, int) | ||
69 | __attribute__((__nonnull__(2))); | ||
70 | |||
71 | static int np_runcmd_close(int); | ||
72 | |||
73 | /* imported from utils.h */ | ||
74 | extern void die (int, const char *, ...) | ||
75 | __attribute__((__noreturn__,__format__(__printf__, 2, 3))); | ||
76 | |||
77 | |||
78 | /* this function is NOT async-safe. It is exported so multithreaded | ||
79 | * plugins (or other apps) can call it prior to running any commands | ||
80 | * through this api and thus achieve async-safeness throughout the api */ | ||
81 | void np_runcmd_init(void) | ||
82 | { | ||
83 | #if !defined(OPEN_MAX) && defined(_SC_OPEN_MAX) | ||
84 | if(!maxfd) { | ||
85 | if((maxfd = sysconf(_SC_OPEN_MAX)) < 0) { | ||
86 | /* possibly log or emit a warning here, since there's no | ||
87 | * guarantee that our guess at maxfd will be adequate */ | ||
88 | maxfd = 256; | ||
89 | } | ||
90 | } | ||
91 | #endif | ||
92 | |||
93 | if(!np_pids) np_pids = calloc(maxfd, sizeof(pid_t)); | ||
94 | } | ||
95 | |||
96 | |||
97 | /* Start running a command */ | ||
98 | static int | ||
99 | np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr) | ||
100 | { | ||
101 | char *env[2]; | ||
102 | char *cmd = NULL; | ||
103 | char **argv = NULL; | ||
104 | char *str; | ||
105 | int argc; | ||
106 | size_t cmdlen; | ||
107 | pid_t pid; | ||
108 | #ifdef RLIMIT_CORE | ||
109 | struct rlimit limit; | ||
110 | #endif | ||
111 | |||
112 | int i = 0; | ||
113 | |||
114 | if(!np_pids) NP_RUNCMD_INIT; | ||
115 | |||
116 | env[0] = strdup("LC_ALL=C"); | ||
117 | env[1] = '\0'; | ||
118 | |||
119 | /* if no command was passed, return with no error */ | ||
120 | if (cmdstring == NULL) | ||
121 | return -1; | ||
122 | |||
123 | /* make copy of command string so strtok() doesn't silently modify it */ | ||
124 | /* (the calling program may want to access it later) */ | ||
125 | cmdlen = strlen(cmdstring); | ||
126 | cmd = malloc(cmdlen + 1); | ||
127 | if (cmd == NULL) return -1; | ||
128 | memcpy(cmd, cmdstring, cmdlen); | ||
129 | |||
130 | /* This is not a shell, so we don't handle "???" */ | ||
131 | if (strstr (cmdstring, "\"")) return -1; | ||
132 | |||
133 | /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */ | ||
134 | if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''")) | ||
135 | return -1; | ||
136 | |||
137 | /* each arg must be whitespace-separated, so args can be a maximum | ||
138 | * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */ | ||
139 | argc = (cmdlen >> 1) + 2; | ||
140 | argv = calloc(sizeof(char *), argc); | ||
141 | |||
142 | if (argv == NULL) { | ||
143 | printf (_("Could not malloc argv array in popen()\n")); | ||
144 | return -1; | ||
145 | } | ||
146 | |||
147 | /* get command arguments (stupidly, but fairly quickly) */ | ||
148 | while (cmd) { | ||
149 | str = cmd; | ||
150 | str += strspn (str, " \t\r\n"); /* trim any leading whitespace */ | ||
151 | |||
152 | if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */ | ||
153 | str++; | ||
154 | if (!strstr (str, "'")) return -1; /* balanced? */ | ||
155 | cmd = 1 + strstr (str, "'"); | ||
156 | str[strcspn (str, "'")] = 0; | ||
157 | } | ||
158 | else { | ||
159 | if (strpbrk (str, " \t\r\n")) { | ||
160 | cmd = 1 + strpbrk (str, " \t\r\n"); | ||
161 | str[strcspn (str, " \t\r\n")] = 0; | ||
162 | } | ||
163 | else { | ||
164 | cmd = NULL; | ||
165 | } | ||
166 | } | ||
167 | |||
168 | if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n")) | ||
169 | cmd = NULL; | ||
170 | |||
171 | argv[i++] = str; | ||
172 | } | ||
173 | |||
174 | if (pipe(pfd) < 0 || pipe(pfderr) < 0 || (pid = fork()) < 0) | ||
175 | return -1; /* errno set by the failing function */ | ||
176 | |||
177 | /* child runs exceve() and _exit. */ | ||
178 | if (pid == 0) { | ||
179 | #ifdef RLIMIT_CORE | ||
180 | /* the program we execve shouldn't leave core files */ | ||
181 | getrlimit (RLIMIT_CORE, &limit); | ||
182 | limit.rlim_cur = 0; | ||
183 | setrlimit (RLIMIT_CORE, &limit); | ||
184 | #endif | ||
185 | close (pfd[0]); | ||
186 | if (pfd[1] != STDOUT_FILENO) { | ||
187 | dup2 (pfd[1], STDOUT_FILENO); | ||
188 | close (pfd[1]); | ||
189 | } | ||
190 | close (pfderr[0]); | ||
191 | if (pfderr[1] != STDERR_FILENO) { | ||
192 | dup2 (pfderr[1], STDERR_FILENO); | ||
193 | close (pfderr[1]); | ||
194 | } | ||
195 | |||
196 | /* close all descriptors in np_pids[] | ||
197 | * This is executed in a separate address space (pure child), | ||
198 | * so we don't have to worry about async safety */ | ||
199 | for (i = 0; i < maxfd; i++) | ||
200 | if(np_pids[i] > 0) | ||
201 | close (i); | ||
202 | |||
203 | execve (argv[0], argv, env); | ||
204 | _exit (0); | ||
205 | } | ||
206 | |||
207 | /* parent picks up execution here */ | ||
208 | /* close childs descriptors in our address space */ | ||
209 | close(pfd[1]); | ||
210 | close(pfderr[1]); | ||
211 | |||
212 | /* tag our file's entry in the pid-list and return it */ | ||
213 | np_pids[pfd[0]] = pid; | ||
214 | |||
215 | return pfd[0]; | ||
216 | } | ||
217 | |||
218 | |||
219 | static int | ||
220 | np_runcmd_close(int fd) | ||
221 | { | ||
222 | int status; | ||
223 | pid_t pid; | ||
224 | |||
225 | /* make sure this fd was opened by popen() */ | ||
226 | if(fd < 0 || fd > maxfd || !np_pids || (pid = np_pids[fd]) == 0) | ||
227 | return -1; | ||
228 | |||
229 | np_pids[fd] = 0; | ||
230 | if (close (fd) == -1) return -1; | ||
231 | |||
232 | /* EINTR is ok (sort of), everything else is bad */ | ||
233 | while (waitpid (pid, &status, 0) < 0) | ||
234 | if (errno != EINTR) return -1; | ||
235 | |||
236 | /* return child's termination status */ | ||
237 | return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1; | ||
238 | } | ||
239 | |||
240 | |||
241 | void | ||
242 | popen_timeout_alarm_handler (int signo) | ||
243 | { | ||
244 | size_t i; | ||
245 | |||
246 | if (signo == SIGALRM) | ||
247 | puts(_("CRITICAL - Plugin timed out while executing system call\n")); | ||
248 | |||
249 | if(np_pids) for(i = 0; i < maxfd; i++) { | ||
250 | if(np_pids[i] != 0) kill(np_pids[i], SIGKILL); | ||
251 | } | ||
252 | |||
253 | exit (STATE_CRITICAL); | ||
254 | } | ||
255 | |||
256 | |||
257 | static int | ||
258 | np_fetch_output(int fd, output *op, int flags) | ||
259 | { | ||
260 | size_t len = 0, i = 0; | ||
261 | size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */ | ||
262 | char *buf = NULL; | ||
263 | int ret; | ||
264 | char tmpbuf[4096]; | ||
265 | |||
266 | op->buf = NULL; | ||
267 | op->buflen = 0; | ||
268 | while((ret = read(fd, tmpbuf, sizeof(tmpbuf))) > 0) { | ||
269 | len = (size_t)ret; | ||
270 | op->buf = realloc(op->buf, op->buflen + len + 1); | ||
271 | memcpy(op->buf + op->buflen, tmpbuf, len); | ||
272 | op->buflen += len; | ||
273 | i++; | ||
274 | } | ||
275 | |||
276 | if(ret < 0) { | ||
277 | printf("read() returned %d: %s\n", ret, strerror(errno)); | ||
278 | return ret; | ||
279 | } | ||
280 | |||
281 | if(!op->buf || !op->buflen) return 0; | ||
282 | |||
283 | /* some plugins may want to keep output unbroken */ | ||
284 | if(flags & RUNCMD_NO_ARRAYS) | ||
285 | return op->buflen; | ||
286 | |||
287 | /* and some may want both (*sigh*) */ | ||
288 | if(flags & RUNCMD_NO_ASSOC) { | ||
289 | buf = malloc(op->buflen); | ||
290 | memcpy(buf, op->buf, op->buflen); | ||
291 | } | ||
292 | else buf = op->buf; | ||
293 | |||
294 | op->line = NULL; | ||
295 | op->lens = NULL; | ||
296 | len = i = 0; | ||
297 | while(i < op->buflen) { | ||
298 | /* make sure we have enough memory */ | ||
299 | if(len >= ary_size) { | ||
300 | ary_size = op->buflen >> --rsf; | ||
301 | op->line = realloc(op->line, ary_size * sizeof(char *)); | ||
302 | op->lens = realloc(op->lens, ary_size * sizeof(size_t)); | ||
303 | } | ||
304 | |||
305 | /* set the pointer to the string */ | ||
306 | op->line[len] = &buf[i]; | ||
307 | |||
308 | /* hop to next newline or end of buffer */ | ||
309 | while(buf[i] != '\n' && i < op->buflen) i++; | ||
310 | buf[i] = '\0'; | ||
311 | |||
312 | /* calculate the string length using pointer difference */ | ||
313 | op->lens[len] = (size_t)&buf[i] - (size_t)op->line[len]; | ||
314 | |||
315 | len++; | ||
316 | i++; | ||
317 | } | ||
318 | |||
319 | return len; | ||
320 | } | ||
321 | |||
322 | |||
323 | int | ||
324 | np_runcmd(const char *cmd, output *out, output *err, int flags) | ||
325 | { | ||
326 | int fd, pfd_out[2], pfd_err[2]; | ||
327 | |||
328 | /* initialize the structs */ | ||
329 | if(out) memset(out, 0, sizeof(output)); | ||
330 | if(err) memset(err, 0, sizeof(output)); | ||
331 | |||
332 | if((fd = np_runcmd_open(cmd, pfd_out, pfd_err)) == -1) | ||
333 | die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd); | ||
334 | |||
335 | if(out) out->lines = np_fetch_output(pfd_out[0], out, flags); | ||
336 | if(err) err->lines = np_fetch_output(pfd_err[0], err, flags); | ||
337 | |||
338 | return np_runcmd_close(fd); | ||
339 | } | ||