check_snmp: add testcase for no datatype
[monitoring-plugins.git] / lib / utils_cmd.c
blob7eb9a3a0c486f21cc34f6bd87729bad37f5571a1
1 /*****************************************************************************
3 * Monitoring run command utilities
5 * License: GPL
6 * Copyright (c) 2005-2006 Monitoring Plugins Development Team
8 * Description :
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 cmd_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 "common.h"
43 #include "utils_cmd.h"
44 #include "utils_base.h"
45 #include <fcntl.h>
47 #ifdef HAVE_SYS_WAIT_H
48 # include <sys/wait.h>
49 #endif
51 /* used in _cmd_open to pass the environment to commands */
52 extern char **environ;
54 /** macros **/
55 #ifndef WEXITSTATUS
56 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
57 #endif
59 #ifndef WIFEXITED
60 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
61 #endif
63 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
64 #if defined(SIG_IGN) && !defined(SIG_ERR)
65 # define SIG_ERR ((Sigfunc *)-1)
66 #endif
68 /* This variable must be global, since there's no way the caller
69 * can forcibly slay a dead or ungainly running program otherwise.
70 * Multithreading apps and plugins can initialize it (via CMD_INIT)
71 * in an async safe manner PRIOR to calling cmd_run() or cmd_run_array()
72 * for the first time.
74 * The check for initialized values is atomic and can
75 * occur in any number of threads simultaneously. */
76 static pid_t *_cmd_pids = NULL;
78 /* Try sysconf(_SC_OPEN_MAX) first, as it can be higher than OPEN_MAX.
79 * If that fails and the macro isn't defined, we fall back to an educated
80 * guess. There's no guarantee that our guess is adequate and the program
81 * will die with SIGSEGV if it isn't and the upper boundary is breached. */
82 #define DEFAULT_MAXFD 256 /* fallback value if no max open files value is set */
83 #define MAXFD_LIMIT 8192 /* upper limit of open files */
84 #ifdef _SC_OPEN_MAX
85 static long maxfd = 0;
86 #elif defined(OPEN_MAX)
87 # define maxfd OPEN_MAX
88 #else /* sysconf macro unavailable, so guess (may be wildly inaccurate) */
89 # define maxfd DEFAULT_MAXFD
90 #endif
93 /** prototypes **/
94 static int _cmd_open (char *const *, int *, int *)
95 __attribute__ ((__nonnull__ (1, 2, 3)));
97 static int _cmd_fetch_output (int, output *, int)
98 __attribute__ ((__nonnull__ (2)));
100 static int _cmd_close (int);
102 /* prototype imported from utils.h */
103 extern void die (int, const char *, ...)
104 __attribute__ ((__noreturn__, __format__ (__printf__, 2, 3)));
107 /* this function is NOT async-safe. It is exported so multithreaded
108 * plugins (or other apps) can call it prior to running any commands
109 * through this api and thus achieve async-safeness throughout the api */
110 void
111 cmd_init (void)
113 #ifndef maxfd
114 if (!maxfd && (maxfd = sysconf (_SC_OPEN_MAX)) < 0) {
115 /* possibly log or emit a warning here, since there's no
116 * guarantee that our guess at maxfd will be adequate */
117 maxfd = DEFAULT_MAXFD;
119 #endif
121 /* if maxfd is unnaturally high, we force it to a lower value
122 * ( e.g. on SunOS, when ulimit is set to unlimited: 2147483647 this would cause
123 * a segfault when following calloc is called ... ) */
125 if ( maxfd > MAXFD_LIMIT ) {
126 maxfd = MAXFD_LIMIT;
129 if (!_cmd_pids)
130 _cmd_pids = calloc (maxfd, sizeof (pid_t));
134 /* Start running a command, array style */
135 static int
136 _cmd_open (char *const *argv, int *pfd, int *pfderr)
138 pid_t pid;
139 #ifdef RLIMIT_CORE
140 struct rlimit limit;
141 #endif
143 int i = 0;
145 /* if no command was passed, return with no error */
146 if (argv == NULL)
147 return -1;
149 if (!_cmd_pids)
150 CMD_INIT;
152 setenv("LC_ALL", "C", 1);
154 if (pipe (pfd) < 0 || pipe (pfderr) < 0 || (pid = fork ()) < 0)
155 return -1; /* errno set by the failing function */
157 /* child runs exceve() and _exit. */
158 if (pid == 0) {
159 #ifdef RLIMIT_CORE
160 /* the program we execve shouldn't leave core files */
161 getrlimit (RLIMIT_CORE, &limit);
162 limit.rlim_cur = 0;
163 setrlimit (RLIMIT_CORE, &limit);
164 #endif
165 close (pfd[0]);
166 if (pfd[1] != STDOUT_FILENO) {
167 dup2 (pfd[1], STDOUT_FILENO);
168 close (pfd[1]);
170 close (pfderr[0]);
171 if (pfderr[1] != STDERR_FILENO) {
172 dup2 (pfderr[1], STDERR_FILENO);
173 close (pfderr[1]);
176 /* close all descriptors in _cmd_pids[]
177 * This is executed in a separate address space (pure child),
178 * so we don't have to worry about async safety */
179 for (i = 0; i < maxfd; i++)
180 if (_cmd_pids[i] > 0)
181 close (i);
183 execve (argv[0], argv, environ);
184 _exit (STATE_UNKNOWN);
187 /* parent picks up execution here */
188 /* close childs descriptors in our address space */
189 close (pfd[1]);
190 close (pfderr[1]);
192 /* tag our file's entry in the pid-list and return it */
193 _cmd_pids[pfd[0]] = pid;
195 return pfd[0];
198 static int
199 _cmd_close (int fd)
201 int status;
202 pid_t pid;
204 /* make sure the provided fd was opened */
205 if (fd < 0 || fd > maxfd || !_cmd_pids || (pid = _cmd_pids[fd]) == 0)
206 return -1;
208 _cmd_pids[fd] = 0;
209 if (close (fd) == -1)
210 return -1;
212 /* EINTR is ok (sort of), everything else is bad */
213 while (waitpid (pid, &status, 0) < 0)
214 if (errno != EINTR)
215 return -1;
217 /* return child's termination status */
218 return (WIFEXITED (status)) ? WEXITSTATUS (status) : -1;
222 static int
223 _cmd_fetch_output (int fd, output * op, int flags)
225 size_t len = 0, i = 0, lineno = 0;
226 size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
227 char *buf = NULL;
228 int ret;
229 char tmpbuf[4096];
231 op->buf = NULL;
232 op->buflen = 0;
233 while ((ret = read (fd, tmpbuf, sizeof (tmpbuf))) > 0) {
234 len = (size_t) ret;
235 op->buf = realloc (op->buf, op->buflen + len + 1);
236 memcpy (op->buf + op->buflen, tmpbuf, len);
237 op->buflen += len;
238 i++;
241 if (ret < 0) {
242 printf ("read() returned %d: %s\n", ret, strerror (errno));
243 return ret;
246 /* some plugins may want to keep output unbroken, and some commands
247 * will yield no output, so return here for those */
248 if (flags & CMD_NO_ARRAYS || !op->buf || !op->buflen)
249 return op->buflen;
251 /* and some may want both */
252 if (flags & CMD_NO_ASSOC) {
253 buf = malloc (op->buflen);
254 memcpy (buf, op->buf, op->buflen);
256 else
257 buf = op->buf;
259 op->line = NULL;
260 op->lens = NULL;
261 i = 0;
262 while (i < op->buflen) {
263 /* make sure we have enough memory */
264 if (lineno >= ary_size) {
265 /* ary_size must never be zero */
266 do {
267 ary_size = op->buflen >> --rsf;
268 } while (!ary_size);
270 op->line = realloc (op->line, ary_size * sizeof (char *));
271 op->lens = realloc (op->lens, ary_size * sizeof (size_t));
274 /* set the pointer to the string */
275 op->line[lineno] = &buf[i];
277 /* hop to next newline or end of buffer */
278 while (buf[i] != '\n' && i < op->buflen)
279 i++;
280 buf[i] = '\0';
282 /* calculate the string length using pointer difference */
283 op->lens[lineno] = (size_t) & buf[i] - (size_t) op->line[lineno];
285 lineno++;
286 i++;
289 return lineno;
294 cmd_run (const char *cmdstring, output * out, output * err, int flags)
296 int fd, pfd_out[2], pfd_err[2];
297 int i = 0, argc;
298 size_t cmdlen;
299 char **argv = NULL;
300 char *cmd = NULL;
301 char *str = NULL;
303 if (cmdstring == NULL)
304 return -1;
306 /* initialize the structs */
307 if (out)
308 memset (out, 0, sizeof (output));
309 if (err)
310 memset (err, 0, sizeof (output));
312 /* make copy of command string so strtok() doesn't silently modify it */
313 /* (the calling program may want to access it later) */
314 cmdlen = strlen (cmdstring);
315 if ((cmd = malloc (cmdlen + 1)) == NULL)
316 return -1;
317 memcpy (cmd, cmdstring, cmdlen);
318 cmd[cmdlen] = '\0';
320 /* This is not a shell, so we don't handle "???" */
321 if (strstr (cmdstring, "\"")) return -1;
323 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
324 if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
325 return -1;
327 /* each arg must be whitespace-separated, so args can be a maximum
328 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
329 argc = (cmdlen >> 1) + 2;
330 argv = calloc (sizeof (char *), argc);
332 if (argv == NULL) {
333 printf ("%s\n", _("Could not malloc argv array in popen()"));
334 return -1;
337 /* get command arguments (stupidly, but fairly quickly) */
338 while (cmd) {
339 str = cmd;
340 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
342 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
343 str++;
344 if (!strstr (str, "'"))
345 return -1; /* balanced? */
346 cmd = 1 + strstr (str, "'");
347 str[strcspn (str, "'")] = 0;
349 else {
350 if (strpbrk (str, " \t\r\n")) {
351 cmd = 1 + strpbrk (str, " \t\r\n");
352 str[strcspn (str, " \t\r\n")] = 0;
354 else {
355 cmd = NULL;
359 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
360 cmd = NULL;
362 argv[i++] = str;
365 return cmd_run_array (argv, out, err, flags);
369 cmd_run_array (char *const *argv, output * out, output * err, int flags)
371 int fd, pfd_out[2], pfd_err[2];
373 /* initialize the structs */
374 if (out)
375 memset (out, 0, sizeof (output));
376 if (err)
377 memset (err, 0, sizeof (output));
379 if ((fd = _cmd_open (argv, pfd_out, pfd_err)) == -1)
380 die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), argv[0]);
382 if (out)
383 out->lines = _cmd_fetch_output (pfd_out[0], out, flags);
384 if (err)
385 err->lines = _cmd_fetch_output (pfd_err[0], err, flags);
387 return _cmd_close (fd);
391 cmd_file_read ( char *filename, output *out, int flags)
393 int fd;
394 if(out)
395 memset (out, 0, sizeof(output));
397 if ((fd = open(filename, O_RDONLY)) == -1) {
398 die( STATE_UNKNOWN, _("Error opening %s: %s"), filename, strerror(errno) );
401 if(out)
402 out->lines = _cmd_fetch_output (fd, out, flags);
404 if (close(fd) == -1)
405 die( STATE_UNKNOWN, _("Error closing %s: %s"), filename, strerror(errno) );
407 return 0;