Update THANKS file
[monitoring-plugins.git] / lib / utils_cmd.c
blob0c853dcc687d99ba2479e43c40edfa5d37fa6f22
1 /*****************************************************************************
3 * Nagios run command utilities
5 * License: GPL
6 * Copyright (c) 2005-2006 Nagios 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 #ifdef _SC_OPEN_MAX
83 static long maxfd = 0;
84 #elif defined(OPEN_MAX)
85 # define maxfd OPEN_MAX
86 #else /* sysconf macro unavailable, so guess (may be wildly inaccurate) */
87 # define maxfd 256
88 #endif
91 /** prototypes **/
92 static int _cmd_open (char *const *, int *, int *)
93 __attribute__ ((__nonnull__ (1, 2, 3)));
95 static int _cmd_fetch_output (int, output *, int)
96 __attribute__ ((__nonnull__ (2)));
98 static int _cmd_close (int);
100 /* prototype imported from utils.h */
101 extern void die (int, const char *, ...)
102 __attribute__ ((__noreturn__, __format__ (__printf__, 2, 3)));
105 /* this function is NOT async-safe. It is exported so multithreaded
106 * plugins (or other apps) can call it prior to running any commands
107 * through this api and thus achieve async-safeness throughout the api */
108 void
109 cmd_init (void)
111 #ifndef maxfd
112 if (!maxfd && (maxfd = sysconf (_SC_OPEN_MAX)) < 0) {
113 /* possibly log or emit a warning here, since there's no
114 * guarantee that our guess at maxfd will be adequate */
115 maxfd = 256;
117 #endif
119 if (!_cmd_pids)
120 _cmd_pids = calloc (maxfd, sizeof (pid_t));
124 /* Start running a command, array style */
125 static int
126 _cmd_open (char *const *argv, int *pfd, int *pfderr)
128 pid_t pid;
129 #ifdef RLIMIT_CORE
130 struct rlimit limit;
131 #endif
133 int i = 0;
135 /* if no command was passed, return with no error */
136 if (argv == NULL)
137 return -1;
139 if (!_cmd_pids)
140 CMD_INIT;
142 setenv("LC_ALL", "C", 1);
144 if (pipe (pfd) < 0 || pipe (pfderr) < 0 || (pid = fork ()) < 0)
145 return -1; /* errno set by the failing function */
147 /* child runs exceve() and _exit. */
148 if (pid == 0) {
149 #ifdef RLIMIT_CORE
150 /* the program we execve shouldn't leave core files */
151 getrlimit (RLIMIT_CORE, &limit);
152 limit.rlim_cur = 0;
153 setrlimit (RLIMIT_CORE, &limit);
154 #endif
155 close (pfd[0]);
156 if (pfd[1] != STDOUT_FILENO) {
157 dup2 (pfd[1], STDOUT_FILENO);
158 close (pfd[1]);
160 close (pfderr[0]);
161 if (pfderr[1] != STDERR_FILENO) {
162 dup2 (pfderr[1], STDERR_FILENO);
163 close (pfderr[1]);
166 /* close all descriptors in _cmd_pids[]
167 * This is executed in a separate address space (pure child),
168 * so we don't have to worry about async safety */
169 for (i = 0; i < maxfd; i++)
170 if (_cmd_pids[i] > 0)
171 close (i);
173 execve (argv[0], argv, environ);
174 _exit (STATE_UNKNOWN);
177 /* parent picks up execution here */
178 /* close childs descriptors in our address space */
179 close (pfd[1]);
180 close (pfderr[1]);
182 /* tag our file's entry in the pid-list and return it */
183 _cmd_pids[pfd[0]] = pid;
185 return pfd[0];
188 static int
189 _cmd_close (int fd)
191 int status;
192 pid_t pid;
194 /* make sure the provided fd was opened */
195 if (fd < 0 || fd > maxfd || !_cmd_pids || (pid = _cmd_pids[fd]) == 0)
196 return -1;
198 _cmd_pids[fd] = 0;
199 if (close (fd) == -1)
200 return -1;
202 /* EINTR is ok (sort of), everything else is bad */
203 while (waitpid (pid, &status, 0) < 0)
204 if (errno != EINTR)
205 return -1;
207 /* return child's termination status */
208 return (WIFEXITED (status)) ? WEXITSTATUS (status) : -1;
212 static int
213 _cmd_fetch_output (int fd, output * op, int flags)
215 size_t len = 0, i = 0, lineno = 0;
216 size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
217 char *buf = NULL;
218 int ret;
219 char tmpbuf[4096];
221 op->buf = NULL;
222 op->buflen = 0;
223 while ((ret = read (fd, tmpbuf, sizeof (tmpbuf))) > 0) {
224 len = (size_t) ret;
225 op->buf = realloc (op->buf, op->buflen + len + 1);
226 memcpy (op->buf + op->buflen, tmpbuf, len);
227 op->buflen += len;
228 i++;
231 if (ret < 0) {
232 printf ("read() returned %d: %s\n", ret, strerror (errno));
233 return ret;
236 /* some plugins may want to keep output unbroken, and some commands
237 * will yield no output, so return here for those */
238 if (flags & CMD_NO_ARRAYS || !op->buf || !op->buflen)
239 return op->buflen;
241 /* and some may want both */
242 if (flags & CMD_NO_ASSOC) {
243 buf = malloc (op->buflen);
244 memcpy (buf, op->buf, op->buflen);
246 else
247 buf = op->buf;
249 op->line = NULL;
250 op->lens = NULL;
251 i = 0;
252 while (i < op->buflen) {
253 /* make sure we have enough memory */
254 if (lineno >= ary_size) {
255 /* ary_size must never be zero */
256 do {
257 ary_size = op->buflen >> --rsf;
258 } while (!ary_size);
260 op->line = realloc (op->line, ary_size * sizeof (char *));
261 op->lens = realloc (op->lens, ary_size * sizeof (size_t));
264 /* set the pointer to the string */
265 op->line[lineno] = &buf[i];
267 /* hop to next newline or end of buffer */
268 while (buf[i] != '\n' && i < op->buflen)
269 i++;
270 buf[i] = '\0';
272 /* calculate the string length using pointer difference */
273 op->lens[lineno] = (size_t) & buf[i] - (size_t) op->line[lineno];
275 lineno++;
276 i++;
279 return lineno;
284 cmd_run (const char *cmdstring, output * out, output * err, int flags)
286 int fd, pfd_out[2], pfd_err[2];
287 int i = 0, argc;
288 size_t cmdlen;
289 char **argv = NULL;
290 char *cmd = NULL;
291 char *str = NULL;
293 if (cmdstring == NULL)
294 return -1;
296 /* initialize the structs */
297 if (out)
298 memset (out, 0, sizeof (output));
299 if (err)
300 memset (err, 0, sizeof (output));
302 /* make copy of command string so strtok() doesn't silently modify it */
303 /* (the calling program may want to access it later) */
304 cmdlen = strlen (cmdstring);
305 if ((cmd = malloc (cmdlen + 1)) == NULL)
306 return -1;
307 memcpy (cmd, cmdstring, cmdlen);
308 cmd[cmdlen] = '\0';
310 /* This is not a shell, so we don't handle "???" */
311 if (strstr (cmdstring, "\"")) return -1;
313 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
314 if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
315 return -1;
317 /* each arg must be whitespace-separated, so args can be a maximum
318 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
319 argc = (cmdlen >> 1) + 2;
320 argv = calloc (sizeof (char *), argc);
322 if (argv == NULL) {
323 printf ("%s\n", _("Could not malloc argv array in popen()"));
324 return -1;
327 /* get command arguments (stupidly, but fairly quickly) */
328 while (cmd) {
329 str = cmd;
330 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
332 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
333 str++;
334 if (!strstr (str, "'"))
335 return -1; /* balanced? */
336 cmd = 1 + strstr (str, "'");
337 str[strcspn (str, "'")] = 0;
339 else {
340 if (strpbrk (str, " \t\r\n")) {
341 cmd = 1 + strpbrk (str, " \t\r\n");
342 str[strcspn (str, " \t\r\n")] = 0;
344 else {
345 cmd = NULL;
349 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
350 cmd = NULL;
352 argv[i++] = str;
355 return cmd_run_array (argv, out, err, flags);
359 cmd_run_array (char *const *argv, output * out, output * err, int flags)
361 int fd, pfd_out[2], pfd_err[2];
363 /* initialize the structs */
364 if (out)
365 memset (out, 0, sizeof (output));
366 if (err)
367 memset (err, 0, sizeof (output));
369 if ((fd = _cmd_open (argv, pfd_out, pfd_err)) == -1)
370 die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), argv[0]);
372 if (out)
373 out->lines = _cmd_fetch_output (pfd_out[0], out, flags);
374 if (err)
375 err->lines = _cmd_fetch_output (pfd_err[0], err, flags);
377 return _cmd_close (fd);
381 cmd_file_read ( char *filename, output *out, int flags)
383 int fd;
384 if(out)
385 memset (out, 0, sizeof(output));
387 if ((fd = open(filename, O_RDONLY)) == -1) {
388 die( STATE_UNKNOWN, _("Error opening %s: %s"), filename, strerror(errno) );
391 if(out)
392 out->lines = _cmd_fetch_output (fd, out, flags);
394 return 0;