Code

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