Revert "check_disk - show all disks if state is ok and option error only is used"
[monitoring-plugins.git] / plugins / runcmd.c
blob1a7c904f9ad11d48058892f77541d6cade547297
1 /*****************************************************************************
2 *
3 * Monitoring run command utilities
4 *
5 * License: GPL
6 * Copyright (c) 2005-2006 Monitoring Plugins Development Team
7 *
8 * Description :
9 *
10 * A simple interface to executing programs from other programs, using an
11 * optimized and safe popen()-like implementation. It is considered safe
12 * in that no shell needs to be spawned and the environment passed to the
13 * execve()'d program is essentially empty.
15 * The code in this file is a derivative of popen.c which in turn was taken
16 * from "Advanced Programming for the Unix Environment" by W. Richard Stevens.
18 * Care has been taken to make sure the functions are async-safe. The one
19 * function which isn't is np_runcmd_init() which it doesn't make sense to
20 * call twice anyway, so the api as a whole should be considered async-safe.
23 * This program is free software: you can redistribute it and/or modify
24 * it under the terms of the GNU General Public License as published by
25 * the Free Software Foundation, either version 3 of the License, or
26 * (at your option) any later version.
28 * This program is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU General Public License for more details.
33 * You should have received a copy of the GNU General Public License
34 * along with this program. If not, see <http://www.gnu.org/licenses/>.
37 *****************************************************************************/
39 #define NAGIOSPLUG_API_C 1
41 /** includes **/
42 #include "runcmd.h"
43 #ifdef HAVE_SYS_WAIT_H
44 # include <sys/wait.h>
45 #endif
47 /** macros **/
48 #ifndef WEXITSTATUS
49 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
50 #endif
52 #ifndef WIFEXITED
53 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
54 #endif
56 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
57 #if defined(SIG_IGN) && !defined(SIG_ERR)
58 # define SIG_ERR ((Sigfunc *)-1)
59 #endif
61 /* This variable must be global, since there's no way the caller
62 * can forcibly slay a dead or ungainly running program otherwise.
63 * Multithreading apps and plugins can initialize it (via NP_RUNCMD_INIT)
64 * in an async safe manner PRIOR to calling np_runcmd() for the first time.
66 * The check for initialized values is atomic and can
67 * occur in any number of threads simultaneously. */
68 static pid_t *np_pids = NULL;
70 /* Try sysconf(_SC_OPEN_MAX) first, as it can be higher than OPEN_MAX.
71 * If that fails and the macro isn't defined, we fall back to an educated
72 * guess. There's no guarantee that our guess is adequate and the program
73 * will die with SIGSEGV if it isn't and the upper boundary is breached. */
74 #ifdef _SC_OPEN_MAX
75 static long maxfd = 0;
76 #elif defined(OPEN_MAX)
77 # define maxfd OPEN_MAX
78 #else /* sysconf macro unavailable, so guess (may be wildly inaccurate) */
79 # define maxfd 256
80 #endif
83 /** prototypes **/
84 static int np_runcmd_open(const char *, int *, int *)
85 __attribute__((__nonnull__(1, 2, 3)));
87 static int np_fetch_output(int, output *, int)
88 __attribute__((__nonnull__(2)));
90 static int np_runcmd_close(int);
92 /* prototype imported from utils.h */
93 extern void die (int, const char *, ...)
94 __attribute__((__noreturn__,__format__(__printf__, 2, 3)));
97 /* this function is NOT async-safe. It is exported so multithreaded
98 * plugins (or other apps) can call it prior to running any commands
99 * through this api and thus achieve async-safeness throughout the api */
100 void np_runcmd_init(void)
102 #ifndef maxfd
103 if(!maxfd && (maxfd = sysconf(_SC_OPEN_MAX)) < 0) {
104 /* possibly log or emit a warning here, since there's no
105 * guarantee that our guess at maxfd will be adequate */
106 maxfd = 256;
108 #endif
110 if(!np_pids) np_pids = calloc(maxfd, sizeof(pid_t));
114 /* Start running a command */
115 static int
116 np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr)
118 char *env[2];
119 char *cmd = NULL;
120 char **argv = NULL;
121 char *str;
122 int argc;
123 size_t cmdlen;
124 pid_t pid;
125 #ifdef RLIMIT_CORE
126 struct rlimit limit;
127 #endif
129 int i = 0;
131 if(!np_pids) NP_RUNCMD_INIT;
133 env[0] = strdup("LC_ALL=C");
134 env[1] = '\0';
136 /* if no command was passed, return with no error */
137 if (cmdstring == NULL)
138 return -1;
140 /* make copy of command string so strtok() doesn't silently modify it */
141 /* (the calling program may want to access it later) */
142 cmdlen = strlen(cmdstring);
143 if((cmd = malloc(cmdlen + 1)) == NULL) return -1;
144 memcpy(cmd, cmdstring, cmdlen);
145 cmd[cmdlen] = '\0';
147 /* This is not a shell, so we don't handle "???" */
148 if (strstr (cmdstring, "\"")) return -1;
150 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
151 if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
152 return -1;
154 /* each arg must be whitespace-separated, so args can be a maximum
155 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
156 argc = (cmdlen >> 1) + 2;
157 argv = calloc(sizeof(char *), argc);
159 if (argv == NULL) {
160 printf ("%s\n", _("Could not malloc argv array in popen()"));
161 return -1;
164 /* get command arguments (stupidly, but fairly quickly) */
165 while (cmd) {
166 str = cmd;
167 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
169 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
170 str++;
171 if (!strstr (str, "'")) return -1; /* balanced? */
172 cmd = 1 + strstr (str, "'");
173 str[strcspn (str, "'")] = 0;
175 else {
176 if (strpbrk (str, " \t\r\n")) {
177 cmd = 1 + strpbrk (str, " \t\r\n");
178 str[strcspn (str, " \t\r\n")] = 0;
180 else {
181 cmd = NULL;
185 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
186 cmd = NULL;
188 argv[i++] = str;
191 if (pipe(pfd) < 0 || pipe(pfderr) < 0 || (pid = fork()) < 0)
192 return -1; /* errno set by the failing function */
194 /* child runs exceve() and _exit. */
195 if (pid == 0) {
196 #ifdef RLIMIT_CORE
197 /* the program we execve shouldn't leave core files */
198 getrlimit (RLIMIT_CORE, &limit);
199 limit.rlim_cur = 0;
200 setrlimit (RLIMIT_CORE, &limit);
201 #endif
202 close (pfd[0]);
203 if (pfd[1] != STDOUT_FILENO) {
204 dup2 (pfd[1], STDOUT_FILENO);
205 close (pfd[1]);
207 close (pfderr[0]);
208 if (pfderr[1] != STDERR_FILENO) {
209 dup2 (pfderr[1], STDERR_FILENO);
210 close (pfderr[1]);
213 /* close all descriptors in np_pids[]
214 * This is executed in a separate address space (pure child),
215 * so we don't have to worry about async safety */
216 for (i = 0; i < maxfd; i++)
217 if(np_pids[i] > 0)
218 close (i);
220 execve (argv[0], argv, env);
221 _exit (STATE_UNKNOWN);
224 /* parent picks up execution here */
225 /* close childs descriptors in our address space */
226 close(pfd[1]);
227 close(pfderr[1]);
229 /* tag our file's entry in the pid-list and return it */
230 np_pids[pfd[0]] = pid;
232 return pfd[0];
236 static int
237 np_runcmd_close(int fd)
239 int status;
240 pid_t pid;
242 /* make sure this fd was opened by popen() */
243 if(fd < 0 || fd > maxfd || !np_pids || (pid = np_pids[fd]) == 0)
244 return -1;
246 np_pids[fd] = 0;
247 if (close (fd) == -1) return -1;
249 /* EINTR is ok (sort of), everything else is bad */
250 while (waitpid (pid, &status, 0) < 0)
251 if (errno != EINTR) return -1;
253 /* return child's termination status */
254 return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1;
258 void
259 runcmd_timeout_alarm_handler (int signo)
261 size_t i;
263 if (signo == SIGALRM)
264 puts(_("CRITICAL - Plugin timed out while executing system call"));
266 if(np_pids) for(i = 0; i < maxfd; i++) {
267 if(np_pids[i] != 0) kill(np_pids[i], SIGKILL);
270 exit (STATE_CRITICAL);
274 static int
275 np_fetch_output(int fd, output *op, int flags)
277 size_t len = 0, i = 0, lineno = 0;
278 size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
279 char *buf = NULL;
280 int ret;
281 char tmpbuf[4096];
283 op->buf = NULL;
284 op->buflen = 0;
285 while((ret = read(fd, tmpbuf, sizeof(tmpbuf))) > 0) {
286 len = (size_t)ret;
287 op->buf = realloc(op->buf, op->buflen + len + 1);
288 memcpy(op->buf + op->buflen, tmpbuf, len);
289 op->buflen += len;
290 i++;
293 if(ret < 0) {
294 printf("read() returned %d: %s\n", ret, strerror(errno));
295 return ret;
298 /* some plugins may want to keep output unbroken, and some commands
299 * will yield no output, so return here for those */
300 if(flags & RUNCMD_NO_ARRAYS || !op->buf || !op->buflen)
301 return op->buflen;
303 /* and some may want both */
304 if(flags & RUNCMD_NO_ASSOC) {
305 buf = malloc(op->buflen);
306 memcpy(buf, op->buf, op->buflen);
308 else buf = op->buf;
310 op->line = NULL;
311 op->lens = NULL;
312 i = 0;
313 while(i < op->buflen) {
314 /* make sure we have enough memory */
315 if(lineno >= ary_size) {
316 /* ary_size must never be zero */
317 do {
318 ary_size = op->buflen >> --rsf;
319 } while(!ary_size);
321 op->line = realloc(op->line, ary_size * sizeof(char *));
322 op->lens = realloc(op->lens, ary_size * sizeof(size_t));
325 /* set the pointer to the string */
326 op->line[lineno] = &buf[i];
328 /* hop to next newline or end of buffer */
329 while(buf[i] != '\n' && i < op->buflen) i++;
330 buf[i] = '\0';
332 /* calculate the string length using pointer difference */
333 op->lens[lineno] = (size_t)&buf[i] - (size_t)op->line[lineno];
335 lineno++;
336 i++;
339 return lineno;
344 np_runcmd(const char *cmd, output *out, output *err, int flags)
346 int fd, pfd_out[2], pfd_err[2];
348 /* initialize the structs */
349 if(out) memset(out, 0, sizeof(output));
350 if(err) memset(err, 0, sizeof(output));
352 if((fd = np_runcmd_open(cmd, pfd_out, pfd_err)) == -1)
353 die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd);
355 if(out) out->lines = np_fetch_output(pfd_out[0], out, flags);
356 if(err) err->lines = np_fetch_output(pfd_err[0], err, flags);
358 return np_runcmd_close(fd);