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 cmd_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 "common.h"
46 #include "utils_cmd.h"
47 #include "utils_base.h"
48 #include <fcntl.h>
50 #ifdef HAVE_SYS_WAIT_H
51 # include <sys/wait.h>
52 #endif
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.
73 *
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)
110 {
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;
116 }
117 #endif
119 if (!_cmd_pids)
120 _cmd_pids = calloc (maxfd, sizeof (pid_t));
121 }
124 /* Start running a command, array style */
125 static int
126 _cmd_open (char *const *argv, int *pfd, int *pfderr)
127 {
128 char *env[2];
129 pid_t pid;
130 #ifdef RLIMIT_CORE
131 struct rlimit limit;
132 #endif
134 int i = 0;
136 /* if no command was passed, return with no error */
137 if (argv == NULL)
138 return -1;
140 if (!_cmd_pids)
141 CMD_INIT;
143 env[0] = strdup ("LC_ALL=C");
144 env[1] = '\0';
146 if (pipe (pfd) < 0 || pipe (pfderr) < 0 || (pid = fork ()) < 0)
147 return -1; /* errno set by the failing function */
149 /* child runs exceve() and _exit. */
150 if (pid == 0) {
151 #ifdef RLIMIT_CORE
152 /* the program we execve shouldn't leave core files */
153 getrlimit (RLIMIT_CORE, &limit);
154 limit.rlim_cur = 0;
155 setrlimit (RLIMIT_CORE, &limit);
156 #endif
157 close (pfd[0]);
158 if (pfd[1] != STDOUT_FILENO) {
159 dup2 (pfd[1], STDOUT_FILENO);
160 close (pfd[1]);
161 }
162 close (pfderr[0]);
163 if (pfderr[1] != STDERR_FILENO) {
164 dup2 (pfderr[1], STDERR_FILENO);
165 close (pfderr[1]);
166 }
168 /* close all descriptors in _cmd_pids[]
169 * This is executed in a separate address space (pure child),
170 * so we don't have to worry about async safety */
171 for (i = 0; i < maxfd; i++)
172 if (_cmd_pids[i] > 0)
173 close (i);
175 execve (argv[0], argv, env);
176 _exit (STATE_UNKNOWN);
177 }
179 /* parent picks up execution here */
180 /* close childs descriptors in our address space */
181 close (pfd[1]);
182 close (pfderr[1]);
184 /* tag our file's entry in the pid-list and return it */
185 _cmd_pids[pfd[0]] = pid;
187 return pfd[0];
188 }
190 static int
191 _cmd_close (int fd)
192 {
193 int status;
194 pid_t pid;
196 /* make sure the provided fd was opened */
197 if (fd < 0 || fd > maxfd || !_cmd_pids || (pid = _cmd_pids[fd]) == 0)
198 return -1;
200 _cmd_pids[fd] = 0;
201 if (close (fd) == -1)
202 return -1;
204 /* EINTR is ok (sort of), everything else is bad */
205 while (waitpid (pid, &status, 0) < 0)
206 if (errno != EINTR)
207 return -1;
209 /* return child's termination status */
210 return (WIFEXITED (status)) ? WEXITSTATUS (status) : -1;
211 }
214 static int
215 _cmd_fetch_output (int fd, output * op, int flags)
216 {
217 size_t len = 0, i = 0, lineno = 0;
218 size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
219 char *buf = NULL;
220 int ret;
221 char tmpbuf[4096];
223 op->buf = NULL;
224 op->buflen = 0;
225 while ((ret = read (fd, tmpbuf, sizeof (tmpbuf))) > 0) {
226 len = (size_t) ret;
227 op->buf = realloc (op->buf, op->buflen + len + 1);
228 memcpy (op->buf + op->buflen, tmpbuf, len);
229 op->buflen += len;
230 i++;
231 }
233 if (ret < 0) {
234 printf ("read() returned %d: %s\n", ret, strerror (errno));
235 return ret;
236 }
238 /* some plugins may want to keep output unbroken, and some commands
239 * will yield no output, so return here for those */
240 if (flags & CMD_NO_ARRAYS || !op->buf || !op->buflen)
241 return op->buflen;
243 /* and some may want both */
244 if (flags & CMD_NO_ASSOC) {
245 buf = malloc (op->buflen);
246 memcpy (buf, op->buf, op->buflen);
247 }
248 else
249 buf = op->buf;
251 op->line = NULL;
252 op->lens = NULL;
253 i = 0;
254 while (i < op->buflen) {
255 /* make sure we have enough memory */
256 if (lineno >= ary_size) {
257 /* ary_size must never be zero */
258 do {
259 ary_size = op->buflen >> --rsf;
260 } while (!ary_size);
262 op->line = realloc (op->line, ary_size * sizeof (char *));
263 op->lens = realloc (op->lens, ary_size * sizeof (size_t));
264 }
266 /* set the pointer to the string */
267 op->line[lineno] = &buf[i];
269 /* hop to next newline or end of buffer */
270 while (buf[i] != '\n' && i < op->buflen)
271 i++;
272 buf[i] = '\0';
274 /* calculate the string length using pointer difference */
275 op->lens[lineno] = (size_t) & buf[i] - (size_t) op->line[lineno];
277 lineno++;
278 i++;
279 }
281 return lineno;
282 }
285 int
286 cmd_run (const char *cmdstring, output * out, output * err, int flags)
287 {
288 int fd, pfd_out[2], pfd_err[2];
289 int i = 0, argc;
290 size_t cmdlen;
291 char **argv = NULL;
292 char *cmd = NULL;
293 char *str = NULL;
295 if (cmdstring == NULL)
296 return -1;
298 /* initialize the structs */
299 if (out)
300 memset (out, 0, sizeof (output));
301 if (err)
302 memset (err, 0, sizeof (output));
304 /* make copy of command string so strtok() doesn't silently modify it */
305 /* (the calling program may want to access it later) */
306 cmdlen = strlen (cmdstring);
307 if ((cmd = malloc (cmdlen + 1)) == NULL)
308 return -1;
309 memcpy (cmd, cmdstring, cmdlen);
310 cmd[cmdlen] = '\0';
312 /* This is not a shell, so we don't handle "???" */
313 if (strstr (cmdstring, "\"")) return -1;
315 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
316 if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
317 return -1;
319 /* each arg must be whitespace-separated, so args can be a maximum
320 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
321 argc = (cmdlen >> 1) + 2;
322 argv = calloc (sizeof (char *), argc);
324 if (argv == NULL) {
325 printf ("%s\n", _("Could not malloc argv array in popen()"));
326 return -1;
327 }
329 /* get command arguments (stupidly, but fairly quickly) */
330 while (cmd) {
331 str = cmd;
332 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
334 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
335 str++;
336 if (!strstr (str, "'"))
337 return -1; /* balanced? */
338 cmd = 1 + strstr (str, "'");
339 str[strcspn (str, "'")] = 0;
340 }
341 else {
342 if (strpbrk (str, " \t\r\n")) {
343 cmd = 1 + strpbrk (str, " \t\r\n");
344 str[strcspn (str, " \t\r\n")] = 0;
345 }
346 else {
347 cmd = NULL;
348 }
349 }
351 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
352 cmd = NULL;
354 argv[i++] = str;
355 }
357 return cmd_run_array (argv, out, err, flags);
358 }
360 int
361 cmd_run_array (char *const *argv, output * out, output * err, int flags)
362 {
363 int fd, pfd_out[2], pfd_err[2];
365 /* initialize the structs */
366 if (out)
367 memset (out, 0, sizeof (output));
368 if (err)
369 memset (err, 0, sizeof (output));
371 if ((fd = _cmd_open (argv, pfd_out, pfd_err)) == -1)
372 die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), argv[0]);
374 if (out)
375 out->lines = _cmd_fetch_output (pfd_out[0], out, flags);
376 if (err)
377 err->lines = _cmd_fetch_output (pfd_err[0], err, flags);
379 return _cmd_close (fd);
380 }
382 int
383 cmd_file_read ( char *filename, output *out, int flags)
384 {
385 int fd;
386 if(out)
387 memset (out, 0, sizeof(output));
389 if ((fd = open(filename, O_RDONLY)) == -1) {
390 die( STATE_UNKNOWN, _("Error opening %s: %s"), filename, strerror(errno) );
391 }
393 if(out)
394 out->lines = _cmd_fetch_output (fd, out, flags);
396 return 0;
397 }