Code

set_thresholds now let the user free the thresolds. (P.S.: When you set twice the...
[nagiosplug.git] / lib / utils_cmd.c
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"
49 #ifdef HAVE_SYS_WAIT_H
50 # include <sys/wait.h>
51 #endif
53 /** macros **/
54 #ifndef WEXITSTATUS
55 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
56 #endif
58 #ifndef WIFEXITED
59 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
60 #endif
62 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
63 #if defined(SIG_IGN) && !defined(SIG_ERR)
64 # define SIG_ERR ((Sigfunc *)-1)
65 #endif
67 /* This variable must be global, since there's no way the caller
68  * can forcibly slay a dead or ungainly running program otherwise.
69  * Multithreading apps and plugins can initialize it (via CMD_INIT)
70  * in an async safe manner PRIOR to calling cmd_run() or cmd_run_array()
71  * for the first time.
72  *
73  * The check for initialized values is atomic and can
74  * occur in any number of threads simultaneously. */
75 static pid_t *_cmd_pids = NULL;
77 /* Try sysconf(_SC_OPEN_MAX) first, as it can be higher than OPEN_MAX.
78  * If that fails and the macro isn't defined, we fall back to an educated
79  * guess. There's no guarantee that our guess is adequate and the program
80  * will die with SIGSEGV if it isn't and the upper boundary is breached. */
81 #ifdef _SC_OPEN_MAX
82 static long maxfd = 0;
83 #elif defined(OPEN_MAX)
84 # define maxfd OPEN_MAX
85 #else   /* sysconf macro unavailable, so guess (may be wildly inaccurate) */
86 # define maxfd 256
87 #endif
90 /** prototypes **/
91 static int _cmd_open (char *const *, int *, int *)
92         __attribute__ ((__nonnull__ (1, 2, 3)));
94 static int _cmd_fetch_output (int, output *, int)
95         __attribute__ ((__nonnull__ (2)));
97 static int _cmd_close (int);
99 /* prototype imported from utils.h */
100 extern void die (int, const char *, ...)
101         __attribute__ ((__noreturn__, __format__ (__printf__, 2, 3)));
104 /* this function is NOT async-safe. It is exported so multithreaded
105  * plugins (or other apps) can call it prior to running any commands
106  * through this api and thus achieve async-safeness throughout the api */
107 void
108 cmd_init (void)
110 #ifndef maxfd
111         if (!maxfd && (maxfd = sysconf (_SC_OPEN_MAX)) < 0) {
112                 /* possibly log or emit a warning here, since there's no
113                  * guarantee that our guess at maxfd will be adequate */
114                 maxfd = 256;
115         }
116 #endif
118         if (!_cmd_pids)
119                 _cmd_pids = calloc (maxfd, sizeof (pid_t));
123 /* Start running a command, array style */
124 static int
125 _cmd_open (char *const *argv, int *pfd, int *pfderr)
127         char *env[2];
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         env[0] = strdup ("LC_ALL=C");
143         env[1] = '\0';
145         if (pipe (pfd) < 0 || pipe (pfderr) < 0 || (pid = fork ()) < 0)
146                 return -1;                                                                      /* errno set by the failing function */
148         /* child runs exceve() and _exit. */
149         if (pid == 0) {
150 #ifdef  RLIMIT_CORE
151                 /* the program we execve shouldn't leave core files */
152                 getrlimit (RLIMIT_CORE, &limit);
153                 limit.rlim_cur = 0;
154                 setrlimit (RLIMIT_CORE, &limit);
155 #endif
156                 close (pfd[0]);
157                 if (pfd[1] != STDOUT_FILENO) {
158                         dup2 (pfd[1], STDOUT_FILENO);
159                         close (pfd[1]);
160                 }
161                 close (pfderr[0]);
162                 if (pfderr[1] != STDERR_FILENO) {
163                         dup2 (pfderr[1], STDERR_FILENO);
164                         close (pfderr[1]);
165                 }
167                 /* close all descriptors in _cmd_pids[]
168                  * This is executed in a separate address space (pure child),
169                  * so we don't have to worry about async safety */
170                 for (i = 0; i < maxfd; i++)
171                         if (_cmd_pids[i] > 0)
172                                 close (i);
174                 execve (argv[0], argv, env);
175                 _exit (STATE_UNKNOWN);
176         }
178         /* parent picks up execution here */
179         /* close childs descriptors in our address space */
180         close (pfd[1]);
181         close (pfderr[1]);
183         /* tag our file's entry in the pid-list and return it */
184         _cmd_pids[pfd[0]] = pid;
186         return pfd[0];
189 static int
190 _cmd_close (int fd)
192         int status;
193         pid_t pid;
195         /* make sure the provided fd was opened */
196         if (fd < 0 || fd > maxfd || !_cmd_pids || (pid = _cmd_pids[fd]) == 0)
197                 return -1;
199         _cmd_pids[fd] = 0;
200         if (close (fd) == -1)
201                 return -1;
203         /* EINTR is ok (sort of), everything else is bad */
204         while (waitpid (pid, &status, 0) < 0)
205                 if (errno != EINTR)
206                         return -1;
208         /* return child's termination status */
209         return (WIFEXITED (status)) ? WEXITSTATUS (status) : -1;
213 static int
214 _cmd_fetch_output (int fd, output * op, int flags)
216         size_t len = 0, i = 0, lineno = 0;
217         size_t rsf = 6, ary_size = 0;   /* rsf = right shift factor, dec'ed uncond once */
218         char *buf = NULL;
219         int ret;
220         char tmpbuf[4096];
222         op->buf = NULL;
223         op->buflen = 0;
224         while ((ret = read (fd, tmpbuf, sizeof (tmpbuf))) > 0) {
225                 len = (size_t) ret;
226                 op->buf = realloc (op->buf, op->buflen + len + 1);
227                 memcpy (op->buf + op->buflen, tmpbuf, len);
228                 op->buflen += len;
229                 i++;
230         }
232         if (ret < 0) {
233                 printf ("read() returned %d: %s\n", ret, strerror (errno));
234                 return ret;
235         }
237         /* some plugins may want to keep output unbroken, and some commands
238          * will yield no output, so return here for those */
239         if (flags & CMD_NO_ARRAYS || !op->buf || !op->buflen)
240                 return op->buflen;
242         /* and some may want both */
243         if (flags & CMD_NO_ASSOC) {
244                 buf = malloc (op->buflen);
245                 memcpy (buf, op->buf, op->buflen);
246         }
247         else
248                 buf = op->buf;
250         op->line = NULL;
251         op->lens = NULL;
252         i = 0;
253         while (i < op->buflen) {
254                 /* make sure we have enough memory */
255                 if (lineno >= ary_size) {
256                         /* ary_size must never be zero */
257                         do {
258                                 ary_size = op->buflen >> --rsf;
259                         } while (!ary_size);
261                         op->line = realloc (op->line, ary_size * sizeof (char *));
262                         op->lens = realloc (op->lens, ary_size * sizeof (size_t));
263                 }
265                 /* set the pointer to the string */
266                 op->line[lineno] = &buf[i];
268                 /* hop to next newline or end of buffer */
269                 while (buf[i] != '\n' && i < op->buflen)
270                         i++;
271                 buf[i] = '\0';
273                 /* calculate the string length using pointer difference */
274                 op->lens[lineno] = (size_t) & buf[i] - (size_t) op->line[lineno];
276                 lineno++;
277                 i++;
278         }
280         return lineno;
284 int
285 cmd_run (const char *cmdstring, output * out, output * err, int flags)
287         int fd, pfd_out[2], pfd_err[2];
288         int i = 0, argc;
289         size_t cmdlen;
290         char **argv = NULL;
291         char *cmd = NULL;
292         char *str = NULL;
294         if (cmdstring == NULL)
295                 return -1;
297         /* initialize the structs */
298         if (out)
299                 memset (out, 0, sizeof (output));
300         if (err)
301                 memset (err, 0, sizeof (output));
303         /* make copy of command string so strtok() doesn't silently modify it */
304         /* (the calling program may want to access it later) */
305         cmdlen = strlen (cmdstring);
306         if ((cmd = malloc (cmdlen + 1)) == NULL)
307                 return -1;
308         memcpy (cmd, cmdstring, cmdlen);
309         cmd[cmdlen] = '\0';
311         /* This is not a shell, so we don't handle "???" */
312         if (strstr (cmdstring, "\"")) return -1;
314         /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
315         if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
316                 return -1;
318         /* each arg must be whitespace-separated, so args can be a maximum
319          * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
320         argc = (cmdlen >> 1) + 2;
321         argv = calloc (sizeof (char *), argc);
323         if (argv == NULL) {
324                 printf ("%s\n", _("Could not malloc argv array in popen()"));
325                 return -1;
326         }
328         /* get command arguments (stupidly, but fairly quickly) */
329         while (cmd) {
330                 str = cmd;
331                 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
333                 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
334                         str++;
335                         if (!strstr (str, "'"))
336                                 return -1;                                                      /* balanced? */
337                         cmd = 1 + strstr (str, "'");
338                         str[strcspn (str, "'")] = 0;
339                 }
340                 else {
341                         if (strpbrk (str, " \t\r\n")) {
342                                 cmd = 1 + strpbrk (str, " \t\r\n");
343                                 str[strcspn (str, " \t\r\n")] = 0;
344                         }
345                         else {
346                                 cmd = NULL;
347                         }
348                 }
350                 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
351                         cmd = NULL;
353                 argv[i++] = str;
354         }
356         return cmd_run_array (argv, out, err, flags);
359 int
360 cmd_run_array (char *const *argv, output * out, output * err, int flags)
362         int fd, pfd_out[2], pfd_err[2];
364         /* initialize the structs */
365         if (out)
366                 memset (out, 0, sizeof (output));
367         if (err)
368                 memset (err, 0, sizeof (output));
370         if ((fd = _cmd_open (argv, pfd_out, pfd_err)) == -1)
371                 die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), argv[0]);
373         if (out)
374                 out->lines = _cmd_fetch_output (pfd_out[0], out, flags);
375         if (err)
376                 err->lines = _cmd_fetch_output (pfd_err[0], err, flags);
378         return _cmd_close (fd);