1 /*****************************************************************************
2 *
3 * Nagios run command utilities
4 *
5 * License: GPL
6 * Copyright (c) 2005-2006 Nagios Plugins Development Team
7 *
8 * Description :
9 *
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.
14 *
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.
17 *
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.
21 *
22 *
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.
27 *
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.
32 *
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/>.
35 *
36 *
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 /** macros **/
52 #ifndef WEXITSTATUS
53 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
54 #endif
56 #ifndef WIFEXITED
57 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
58 #endif
60 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
61 #if defined(SIG_IGN) && !defined(SIG_ERR)
62 # define SIG_ERR ((Sigfunc *)-1)
63 #endif
65 /* This variable must be global, since there's no way the caller
66 * can forcibly slay a dead or ungainly running program otherwise.
67 * Multithreading apps and plugins can initialize it (via CMD_INIT)
68 * in an async safe manner PRIOR to calling cmd_run() or cmd_run_array()
69 * for the first time.
70 *
71 * The check for initialized values is atomic and can
72 * occur in any number of threads simultaneously. */
73 static pid_t *_cmd_pids = NULL;
75 /* Try sysconf(_SC_OPEN_MAX) first, as it can be higher than OPEN_MAX.
76 * If that fails and the macro isn't defined, we fall back to an educated
77 * guess. There's no guarantee that our guess is adequate and the program
78 * will die with SIGSEGV if it isn't and the upper boundary is breached. */
79 #ifdef _SC_OPEN_MAX
80 static long maxfd = 0;
81 #elif defined(OPEN_MAX)
82 # define maxfd OPEN_MAX
83 #else /* sysconf macro unavailable, so guess (may be wildly inaccurate) */
84 # define maxfd 256
85 #endif
88 /** prototypes **/
89 static int _cmd_open (char *const *, int *, int *)
90 __attribute__ ((__nonnull__ (1, 2, 3)));
92 static int _cmd_fetch_output (int, output *, int)
93 __attribute__ ((__nonnull__ (2)));
95 static int _cmd_close (int);
97 /* prototype imported from utils.h */
98 extern void die (int, const char *, ...)
99 __attribute__ ((__noreturn__, __format__ (__printf__, 2, 3)));
102 /* this function is NOT async-safe. It is exported so multithreaded
103 * plugins (or other apps) can call it prior to running any commands
104 * through this api and thus achieve async-safeness throughout the api */
105 void
106 cmd_init (void)
107 {
108 #ifndef maxfd
109 if (!maxfd && (maxfd = sysconf (_SC_OPEN_MAX)) < 0) {
110 /* possibly log or emit a warning here, since there's no
111 * guarantee that our guess at maxfd will be adequate */
112 maxfd = 256;
113 }
114 #endif
116 if (!_cmd_pids)
117 _cmd_pids = calloc (maxfd, sizeof (pid_t));
118 }
121 /* Start running a command, array style */
122 static int
123 _cmd_open (char *const *argv, int *pfd, int *pfderr)
124 {
125 char *env[2];
126 pid_t pid;
127 #ifdef RLIMIT_CORE
128 struct rlimit limit;
129 #endif
131 int i = 0;
133 /* if no command was passed, return with no error */
134 if (argv == NULL)
135 return -1;
137 if (!_cmd_pids)
138 CMD_INIT;
140 env[0] = strdup ("LC_ALL=C");
141 env[1] = '\0';
143 if (pipe (pfd) < 0 || pipe (pfderr) < 0 || (pid = fork ()) < 0)
144 return -1; /* errno set by the failing function */
146 /* child runs exceve() and _exit. */
147 if (pid == 0) {
148 #ifdef RLIMIT_CORE
149 /* the program we execve shouldn't leave core files */
150 getrlimit (RLIMIT_CORE, &limit);
151 limit.rlim_cur = 0;
152 setrlimit (RLIMIT_CORE, &limit);
153 #endif
154 close (pfd[0]);
155 if (pfd[1] != STDOUT_FILENO) {
156 dup2 (pfd[1], STDOUT_FILENO);
157 close (pfd[1]);
158 }
159 close (pfderr[0]);
160 if (pfderr[1] != STDERR_FILENO) {
161 dup2 (pfderr[1], STDERR_FILENO);
162 close (pfderr[1]);
163 }
165 /* close all descriptors in _cmd_pids[]
166 * This is executed in a separate address space (pure child),
167 * so we don't have to worry about async safety */
168 for (i = 0; i < maxfd; i++)
169 if (_cmd_pids[i] > 0)
170 close (i);
172 execve (argv[0], argv, env);
173 _exit (STATE_UNKNOWN);
174 }
176 /* parent picks up execution here */
177 /* close childs descriptors in our address space */
178 close (pfd[1]);
179 close (pfderr[1]);
181 /* tag our file's entry in the pid-list and return it */
182 _cmd_pids[pfd[0]] = pid;
184 return pfd[0];
185 }
187 static int
188 _cmd_close (int fd)
189 {
190 int status;
191 pid_t pid;
193 /* make sure the provided fd was opened */
194 if (fd < 0 || fd > maxfd || !_cmd_pids || (pid = _cmd_pids[fd]) == 0)
195 return -1;
197 _cmd_pids[fd] = 0;
198 if (close (fd) == -1)
199 return -1;
201 /* EINTR is ok (sort of), everything else is bad */
202 while (waitpid (pid, &status, 0) < 0)
203 if (errno != EINTR)
204 return -1;
206 /* return child's termination status */
207 return (WIFEXITED (status)) ? WEXITSTATUS (status) : -1;
208 }
211 static int
212 _cmd_fetch_output (int fd, output * op, int flags)
213 {
214 size_t len = 0, i = 0, lineno = 0;
215 size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
216 char *buf = NULL;
217 int ret;
218 char tmpbuf[4096];
220 op->buf = NULL;
221 op->buflen = 0;
222 while ((ret = read (fd, tmpbuf, sizeof (tmpbuf))) > 0) {
223 len = (size_t) ret;
224 op->buf = realloc (op->buf, op->buflen + len + 1);
225 memcpy (op->buf + op->buflen, tmpbuf, len);
226 op->buflen += len;
227 i++;
228 }
230 if (ret < 0) {
231 printf ("read() returned %d: %s\n", ret, strerror (errno));
232 return ret;
233 }
235 /* some plugins may want to keep output unbroken, and some commands
236 * will yield no output, so return here for those */
237 if (flags & CMD_NO_ARRAYS || !op->buf || !op->buflen)
238 return op->buflen;
240 /* and some may want both */
241 if (flags & CMD_NO_ASSOC) {
242 buf = malloc (op->buflen);
243 memcpy (buf, op->buf, op->buflen);
244 }
245 else
246 buf = op->buf;
248 op->line = NULL;
249 op->lens = NULL;
250 i = 0;
251 while (i < op->buflen) {
252 /* make sure we have enough memory */
253 if (lineno >= ary_size) {
254 /* ary_size must never be zero */
255 do {
256 ary_size = op->buflen >> --rsf;
257 } while (!ary_size);
259 op->line = realloc (op->line, ary_size * sizeof (char *));
260 op->lens = realloc (op->lens, ary_size * sizeof (size_t));
261 }
263 /* set the pointer to the string */
264 op->line[lineno] = &buf[i];
266 /* hop to next newline or end of buffer */
267 while (buf[i] != '\n' && i < op->buflen)
268 i++;
269 buf[i] = '\0';
271 /* calculate the string length using pointer difference */
272 op->lens[lineno] = (size_t) & buf[i] - (size_t) op->line[lineno];
274 lineno++;
275 i++;
276 }
278 return lineno;
279 }
282 int
283 cmd_run (const char *cmdstring, output * out, output * err, int flags)
284 {
285 int fd, pfd_out[2], pfd_err[2];
286 int i = 0, argc;
287 size_t cmdlen;
288 char **argv = NULL;
289 char *cmd = NULL;
290 char *str = NULL;
292 if (cmdstring == NULL)
293 return -1;
295 /* initialize the structs */
296 if (out)
297 memset (out, 0, sizeof (output));
298 if (err)
299 memset (err, 0, sizeof (output));
301 /* make copy of command string so strtok() doesn't silently modify it */
302 /* (the calling program may want to access it later) */
303 cmdlen = strlen (cmdstring);
304 if ((cmd = malloc (cmdlen + 1)) == NULL)
305 return -1;
306 memcpy (cmd, cmdstring, cmdlen);
307 cmd[cmdlen] = '\0';
309 /* This is not a shell, so we don't handle "???" */
310 if (strstr (cmdstring, "\"")) return -1;
312 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
313 if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
314 return -1;
316 /* each arg must be whitespace-separated, so args can be a maximum
317 * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
318 argc = (cmdlen >> 1) + 2;
319 argv = calloc (sizeof (char *), argc);
321 if (argv == NULL) {
322 printf ("%s\n", _("Could not malloc argv array in popen()"));
323 return -1;
324 }
326 /* get command arguments (stupidly, but fairly quickly) */
327 while (cmd) {
328 str = cmd;
329 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
331 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
332 str++;
333 if (!strstr (str, "'"))
334 return -1; /* balanced? */
335 cmd = 1 + strstr (str, "'");
336 str[strcspn (str, "'")] = 0;
337 }
338 else {
339 if (strpbrk (str, " \t\r\n")) {
340 cmd = 1 + strpbrk (str, " \t\r\n");
341 str[strcspn (str, " \t\r\n")] = 0;
342 }
343 else {
344 cmd = NULL;
345 }
346 }
348 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
349 cmd = NULL;
351 argv[i++] = str;
352 }
354 return cmd_run_array (argv, out, err, flags);
355 }
357 int
358 cmd_run_array (char *const *argv, output * out, output * err, int flags)
359 {
360 int fd, pfd_out[2], pfd_err[2];
362 /* initialize the structs */
363 if (out)
364 memset (out, 0, sizeof (output));
365 if (err)
366 memset (err, 0, sizeof (output));
368 if ((fd = _cmd_open (argv, pfd_out, pfd_err)) == -1)
369 die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), argv[0]);
371 if (out)
372 out->lines = _cmd_fetch_output (pfd_out[0], out, flags);
373 if (err)
374 err->lines = _cmd_fetch_output (pfd_err[0], err, flags);
376 return _cmd_close (fd);
377 }
379 int
380 cmd_file_read ( char *filename, output *out, int flags)
381 {
382 int fd;
383 if(out)
384 memset (out, 0, sizeof(output));
386 if ((fd = open(filename, O_RDONLY)) == -1) {
387 die( STATE_UNKNOWN, _("Error opening %s: %s"), filename, strerror(errno) );
388 }
390 if(out)
391 out->lines = _cmd_fetch_output (fd, out, flags);
393 return 0;
394 }