Fix INADDR_NONE value (for systems which don't define it).
[monitoring-plugins.git] / plugins / runcmd.c
blobaf12d22431010fec84314e3163b79bb4a21e329b
1 /****************************************************************************
2 * Nagios run command utilities
4 * License: GPL
5 * Copyright (c) 2005 nagios-plugins team
7 * $Id$
9 * Description :
11 * A simple interface to executing programs from other programs, using an
12 * optimized and safe popen()-like implementation. It is considered safe
13 * in that no shell needs to be spawned and the environment passed to the
14 * execve()'d program is essentially empty.
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.
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.
24 * License Information:
26 * This program is free software; you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as published by
28 * the Free Software Foundation; either version 2 of the License, or
29 * (at your option) any later version.
31 * This program is distributed in the hope that it will be useful,
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
36 * You should have received a copy of the GNU General Public License
37 * along with this program; if not, write to the Free Software
38 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
41 #define NAGIOSPLUG_API_C 1
43 /** includes **/
44 #include "runcmd.h"
45 #ifdef HAVE_SYS_WAIT_H
46 # include <sys/wait.h>
47 #endif
49 /** macros **/
50 #ifndef WEXITSTATUS
51 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
52 #endif
54 #ifndef WIFEXITED
55 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
56 #endif
58 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
59 #if defined(SIG_IGN) && !defined(SIG_ERR)
60 # define SIG_ERR ((Sigfunc *)-1)
61 #endif
63 /* This variable must be global, since there's no way the caller
64 * can forcibly slay a dead or ungainly running program otherwise.
65 * Multithreading apps and plugins can initialize it (via NP_RUNCMD_INIT)
66 * in an async safe manner PRIOR to calling np_runcmd() for the first time.
68 * The check for initialized values is atomic and can
69 * occur in any number of threads simultaneously. */
70 static pid_t *np_pids = NULL;
72 /* Try sysconf(_SC_OPEN_MAX) first, as it can be higher than OPEN_MAX.
73 * If that fails and the macro isn't defined, we fall back to an educated
74 * guess. There's no guarantee that our guess is adequate and the program
75 * will die with SIGSEGV if it isn't and the upper boundary is breached. */
76 #ifdef _SC_OPEN_MAX
77 static long maxfd = 0;
78 #elif defined(OPEN_MAX)
79 # define maxfd OPEN_MAX
80 #else /* sysconf macro unavailable, so guess (may be wildly inaccurate) */
81 # define maxfd 256
82 #endif
85 /** prototypes **/
86 static int np_runcmd_open(const char *, int *, int *)
87 __attribute__((__nonnull__(1, 2, 3)));
89 static int np_fetch_output(int, output *, int)
90 __attribute__((__nonnull__(2)));
92 static int np_runcmd_close(int);
94 /* prototype imported from utils.h */
95 extern void die (int, const char *, ...)
96 __attribute__((__noreturn__,__format__(__printf__, 2, 3)));
99 /* this function is NOT async-safe. It is exported so multithreaded
100 * plugins (or other apps) can call it prior to running any commands
101 * through this api and thus achieve async-safeness throughout the api */
102 void np_runcmd_init(void)
104 #ifndef maxfd
105 if(!maxfd && (maxfd = sysconf(_SC_OPEN_MAX)) < 0) {
106 /* possibly log or emit a warning here, since there's no
107 * guarantee that our guess at maxfd will be adequate */
108 maxfd = 256;
110 #endif
112 if(!np_pids) np_pids = calloc(maxfd, sizeof(pid_t));
116 /* Start running a command */
117 static int
118 np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr)
120 char *env[2];
121 char *cmd = NULL;
122 char **argv = NULL;
123 char *str;
124 int argc;
125 size_t cmdlen;
126 pid_t pid;
127 #ifdef RLIMIT_CORE
128 struct rlimit limit;
129 #endif
131 int i = 0;
133 if(!np_pids) NP_RUNCMD_INIT;
135 env[0] = strdup("LC_ALL=C");
136 env[1] = '\0';
138 /* if no command was passed, return with no error */
139 if (cmdstring == NULL)
140 return -1;
142 /* make copy of command string so strtok() doesn't silently modify it */
143 /* (the calling program may want to access it later) */
144 cmdlen = strlen(cmdstring);
145 if((cmd = malloc(cmdlen + 1)) == NULL) return -1;
146 memcpy(cmd, cmdstring, cmdlen);
147 cmd[cmdlen] = '\0';
149 /* This is not a shell, so we don't handle "???" */
150 if (strstr (cmdstring, "\"")) return -1;
152 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
153 if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
154 return -1;
156 /* each arg must be whitespace-separated, so args can be a maximum
157 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
158 argc = (cmdlen >> 1) + 2;
159 argv = calloc(sizeof(char *), argc);
161 if (argv == NULL) {
162 printf ("%s\n", _("Could not malloc argv array in popen()"));
163 return -1;
166 /* get command arguments (stupidly, but fairly quickly) */
167 while (cmd) {
168 str = cmd;
169 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
171 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
172 str++;
173 if (!strstr (str, "'")) return -1; /* balanced? */
174 cmd = 1 + strstr (str, "'");
175 str[strcspn (str, "'")] = 0;
177 else {
178 if (strpbrk (str, " \t\r\n")) {
179 cmd = 1 + strpbrk (str, " \t\r\n");
180 str[strcspn (str, " \t\r\n")] = 0;
182 else {
183 cmd = NULL;
187 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
188 cmd = NULL;
190 argv[i++] = str;
193 if (pipe(pfd) < 0 || pipe(pfderr) < 0 || (pid = fork()) < 0)
194 return -1; /* errno set by the failing function */
196 /* child runs exceve() and _exit. */
197 if (pid == 0) {
198 #ifdef RLIMIT_CORE
199 /* the program we execve shouldn't leave core files */
200 getrlimit (RLIMIT_CORE, &limit);
201 limit.rlim_cur = 0;
202 setrlimit (RLIMIT_CORE, &limit);
203 #endif
204 close (pfd[0]);
205 if (pfd[1] != STDOUT_FILENO) {
206 dup2 (pfd[1], STDOUT_FILENO);
207 close (pfd[1]);
209 close (pfderr[0]);
210 if (pfderr[1] != STDERR_FILENO) {
211 dup2 (pfderr[1], STDERR_FILENO);
212 close (pfderr[1]);
215 /* close all descriptors in np_pids[]
216 * This is executed in a separate address space (pure child),
217 * so we don't have to worry about async safety */
218 for (i = 0; i < maxfd; i++)
219 if(np_pids[i] > 0)
220 close (i);
222 execve (argv[0], argv, env);
223 _exit (STATE_UNKNOWN);
226 /* parent picks up execution here */
227 /* close childs descriptors in our address space */
228 close(pfd[1]);
229 close(pfderr[1]);
231 /* tag our file's entry in the pid-list and return it */
232 np_pids[pfd[0]] = pid;
234 return pfd[0];
238 static int
239 np_runcmd_close(int fd)
241 int status;
242 pid_t pid;
244 /* make sure this fd was opened by popen() */
245 if(fd < 0 || fd > maxfd || !np_pids || (pid = np_pids[fd]) == 0)
246 return -1;
248 np_pids[fd] = 0;
249 if (close (fd) == -1) return -1;
251 /* EINTR is ok (sort of), everything else is bad */
252 while (waitpid (pid, &status, 0) < 0)
253 if (errno != EINTR) return -1;
255 /* return child's termination status */
256 return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1;
260 void
261 popen_timeout_alarm_handler (int signo)
263 size_t i;
265 if (signo == SIGALRM)
266 puts(_("CRITICAL - Plugin timed out while executing system call\n"));
268 if(np_pids) for(i = 0; i < maxfd; i++) {
269 if(np_pids[i] != 0) kill(np_pids[i], SIGKILL);
272 exit (STATE_CRITICAL);
276 static int
277 np_fetch_output(int fd, output *op, int flags)
279 size_t len = 0, i = 0, lineno = 0;
280 size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
281 char *buf = NULL;
282 int ret;
283 char tmpbuf[4096];
285 op->buf = NULL;
286 op->buflen = 0;
287 while((ret = read(fd, tmpbuf, sizeof(tmpbuf))) > 0) {
288 len = (size_t)ret;
289 op->buf = realloc(op->buf, op->buflen + len + 1);
290 memcpy(op->buf + op->buflen, tmpbuf, len);
291 op->buflen += len;
292 i++;
295 if(ret < 0) {
296 printf("read() returned %d: %s\n", ret, strerror(errno));
297 return ret;
300 /* some plugins may want to keep output unbroken, and some commands
301 * will yield no output, so return here for those */
302 if(flags & RUNCMD_NO_ARRAYS || !op->buf || !op->buflen)
303 return op->buflen;
305 /* and some may want both */
306 if(flags & RUNCMD_NO_ASSOC) {
307 buf = malloc(op->buflen);
308 memcpy(buf, op->buf, op->buflen);
310 else buf = op->buf;
312 op->line = NULL;
313 op->lens = NULL;
314 i = 0;
315 while(i < op->buflen) {
316 /* make sure we have enough memory */
317 if(lineno >= ary_size) {
318 /* ary_size must never be zero */
319 do {
320 ary_size = op->buflen >> --rsf;
321 } while(!ary_size);
323 op->line = realloc(op->line, ary_size * sizeof(char *));
324 op->lens = realloc(op->lens, ary_size * sizeof(size_t));
327 /* set the pointer to the string */
328 op->line[lineno] = &buf[i];
330 /* hop to next newline or end of buffer */
331 while(buf[i] != '\n' && i < op->buflen) i++;
332 buf[i] = '\0';
334 /* calculate the string length using pointer difference */
335 op->lens[lineno] = (size_t)&buf[i] - (size_t)op->line[lineno];
337 lineno++;
338 i++;
341 return lineno;
346 np_runcmd(const char *cmd, output *out, output *err, int flags)
348 int fd, pfd_out[2], pfd_err[2];
350 /* initialize the structs */
351 if(out) memset(out, 0, sizeof(output));
352 if(err) memset(err, 0, sizeof(output));
354 if((fd = np_runcmd_open(cmd, pfd_out, pfd_err)) == -1)
355 die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd);
357 if(out) out->lines = np_fetch_output(pfd_out[0], out, flags);
358 if(err) err->lines = np_fetch_output(pfd_err[0], err, flags);
360 return np_runcmd_close(fd);