Code

4155796c5575730d74d746a5e4d9fdf0ad2529ab
[nagiosplug.git] / plugins / runcmd.c
1 /*
2  * $Id$
3  *
4  * A simple interface to executing programs from other programs, using an
5  * optimized and safe popen()-like implementation. It is considered safe
6  * in that no shell needs to be spawned and the environment passed to the
7  * execve()'d program is essentially empty.
8  *
9  *
10  * The code in this file is a derivative of popen.c which in turn was taken
11  * from "Advanced Programming for the Unix Environment" by W. Richard Stevens.
12  *
13  * Care has been taken to make sure the functions are async-safe. The one
14  * function which isn't is np_runcmd_init() which it doesn't make sense to
15  * call twice anyway, so the api as a whole should be considered async-safe.
16  *
17  */
19 #define NAGIOSPLUG_API_C 1
21 /** includes **/
22 #include "runcmd.h"
23 #ifdef HAVE_SYS_WAIT_H
24 # include <sys/wait.h>
25 #endif
27 /** macros **/
28 #ifndef WEXITSTATUS
29 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
30 #endif
32 #ifndef WIFEXITED
33 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
34 #endif
36 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
37 #if defined(SIG_IGN) && !defined(SIG_ERR)
38 # define SIG_ERR ((Sigfunc *)-1)
39 #endif
41 /* This variable must be global, since there's no way the caller
42  * can forcibly slay a dead or ungainly running program otherwise.
43  * Multithreading apps and plugins can initialize it (via NP_RUNCMD_INIT)
44  * in an async safe manner PRIOR to calling np_runcmd() for the first time.
45  *
46  * The check for initialized values is atomic and can
47  * occur in any number of threads simultaneously. */
48 static pid_t *np_pids = NULL;
50 /* Try sysconf(_SC_OPEN_MAX) first, as it can be higher than OPEN_MAX.
51  * If that fails and the macro isn't defined, we fall back to an educated
52  * guess. There's no guarantee that our guess is adequate and the program
53  * will die with SIGSEGV if it isn't and the upper boundary is breached. */
54 #ifdef _SC_OPEN_MAX
55 static long maxfd = 0;
56 #elif defined(OPEN_MAX)
57 # define maxfd OPEN_MAX
58 #else /* sysconf macro unavailable, so guess (may be wildly inaccurate) */
59 # define maxfd 256
60 #endif
63 /** prototypes **/
64 static int np_runcmd_open(const char *, int *, int *)
65         __attribute__((__nonnull__(1, 2, 3)));
67 static int np_fetch_output(int, output *, int)
68         __attribute__((__nonnull__(2)));
70 static int np_runcmd_close(int);
72 /* prototype imported from utils.h */
73 extern void die (int, const char *, ...)
74         __attribute__((__noreturn__,__format__(__printf__, 2, 3)));
77 /* this function is NOT async-safe. It is exported so multithreaded
78  * plugins (or other apps) can call it prior to running any commands
79  * through this api and thus achieve async-safeness throughout the api */
80 void np_runcmd_init(void)
81 {
82 #ifndef maxfd
83         if(!maxfd && (maxfd = sysconf(_SC_OPEN_MAX)) < 0) {
84                 /* possibly log or emit a warning here, since there's no
85                  * guarantee that our guess at maxfd will be adequate */
86                 maxfd = 256;
87         }
88 #endif
90         if(!np_pids) np_pids = calloc(maxfd, sizeof(pid_t));
91 }
94 /* Start running a command */
95 static int
96 np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr)
97 {
98         char *env[2];
99         char *cmd = NULL;
100         char **argv = NULL;
101         char *str;
102         int argc;
103         size_t cmdlen;
104         pid_t pid;
105 #ifdef RLIMIT_CORE
106         struct rlimit limit;
107 #endif
109         int i = 0;
111         if(!np_pids) NP_RUNCMD_INIT;
113         env[0] = strdup("LC_ALL=C");
114         env[1] = '\0';
116         /* if no command was passed, return with no error */
117         if (cmdstring == NULL)
118                 return -1;
120         /* make copy of command string so strtok() doesn't silently modify it */
121         /* (the calling program may want to access it later) */
122         cmdlen = strlen(cmdstring);
123         if((cmd = malloc(cmdlen + 1)) == NULL) return -1;
124         memcpy(cmd, cmdstring, cmdlen);
125         cmd[cmdlen] = '\0';
127         /* This is not a shell, so we don't handle "???" */
128         if (strstr (cmdstring, "\"")) return -1;
130         /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
131         if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
132                 return -1;
134         /* each arg must be whitespace-separated, so args can be a maximum
135          * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
136         argc = (cmdlen >> 1) + 2;
137         argv = calloc(sizeof(char *), argc);
139         if (argv == NULL) {
140                 printf (_("Could not malloc argv array in popen()\n"));
141                 return -1;
142         }
144         /* get command arguments (stupidly, but fairly quickly) */
145         while (cmd) {
146                 str = cmd;
147                 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
149                 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
150                         str++;
151                         if (!strstr (str, "'")) return -1;      /* balanced? */
152                         cmd = 1 + strstr (str, "'");
153                         str[strcspn (str, "'")] = 0;
154                 }
155                 else {
156                         if (strpbrk (str, " \t\r\n")) {
157                                 cmd = 1 + strpbrk (str, " \t\r\n");
158                                 str[strcspn (str, " \t\r\n")] = 0;
159                         }
160                         else {
161                                 cmd = NULL;
162                         }
163                 }
165                 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
166                         cmd = NULL;
168                 argv[i++] = str;
169         }
171         if (pipe(pfd) < 0 || pipe(pfderr) < 0 || (pid = fork()) < 0)
172                 return -1; /* errno set by the failing function */
174         /* child runs exceve() and _exit. */
175         if (pid == 0) {
176 #ifdef  RLIMIT_CORE
177                 /* the program we execve shouldn't leave core files */
178                 getrlimit (RLIMIT_CORE, &limit);
179                 limit.rlim_cur = 0;
180                 setrlimit (RLIMIT_CORE, &limit);
181 #endif
182                 close (pfd[0]);
183                 if (pfd[1] != STDOUT_FILENO) {
184                         dup2 (pfd[1], STDOUT_FILENO);
185                         close (pfd[1]);
186                 }
187                 close (pfderr[0]);
188                 if (pfderr[1] != STDERR_FILENO) {
189                         dup2 (pfderr[1], STDERR_FILENO);
190                         close (pfderr[1]);
191                 }
193                 /* close all descriptors in np_pids[]
194                  * This is executed in a separate address space (pure child),
195                  * so we don't have to worry about async safety */
196                 for (i = 0; i < maxfd; i++)
197                         if(np_pids[i] > 0)
198                                 close (i);
200                 execve (argv[0], argv, env);
201                 _exit (0);
202         }
204         /* parent picks up execution here */
205         /* close childs descriptors in our address space */
206         close(pfd[1]);
207         close(pfderr[1]);
209         /* tag our file's entry in the pid-list and return it */
210         np_pids[pfd[0]] = pid;
212         return pfd[0];
216 static int
217 np_runcmd_close(int fd)
219         int status;
220         pid_t pid;
222         /* make sure this fd was opened by popen() */
223         if(fd < 0 || fd > maxfd || !np_pids || (pid = np_pids[fd]) == 0)
224                 return -1;
226         np_pids[fd] = 0;
227         if (close (fd) == -1) return -1;
229         /* EINTR is ok (sort of), everything else is bad */
230         while (waitpid (pid, &status, 0) < 0)
231                 if (errno != EINTR) return -1;
233         /* return child's termination status */
234         return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1;
238 void
239 popen_timeout_alarm_handler (int signo)
241         size_t i;
243         if (signo == SIGALRM)
244                 puts(_("CRITICAL - Plugin timed out while executing system call\n"));
246         if(np_pids) for(i = 0; i < maxfd; i++) {
247                 if(np_pids[i] != 0) kill(np_pids[i], SIGKILL);
248         }
250         exit (STATE_CRITICAL);
254 static int
255 np_fetch_output(int fd, output *op, int flags)
257         size_t len = 0, i = 0, lineno = 0;
258         size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
259         char *buf = NULL;
260         int ret;
261         char tmpbuf[4096];
263         op->buf = NULL;
264         op->buflen = 0;
265         while((ret = read(fd, tmpbuf, sizeof(tmpbuf))) > 0) {
266                 len = (size_t)ret;
267                 op->buf = realloc(op->buf, op->buflen + len + 1);
268                 memcpy(op->buf + op->buflen, tmpbuf, len);
269                 op->buflen += len;
270                 i++;
271         }
273         if(ret < 0) {
274                 printf("read() returned %d: %s\n", ret, strerror(errno));
275                 return ret;
276         }
278         /* some plugins may want to keep output unbroken, and some commands
279          * will yield no output, so return here for those */
280         if(flags & RUNCMD_NO_ARRAYS || !op->buf || !op->buflen)
281                 return op->buflen;
283         /* and some may want both */
284         if(flags & RUNCMD_NO_ASSOC) {
285                 buf = malloc(op->buflen);
286                 memcpy(buf, op->buf, op->buflen);
287         }
288         else buf = op->buf;
290         op->line = NULL;
291         op->lens = NULL;
292         i = 0;
293         while(i < op->buflen) {
294                 /* make sure we have enough memory */
295                 if(lineno >= ary_size) {
296                         /* ary_size must never be zero */
297                         do {
298                                 ary_size = op->buflen >> --rsf;
299                         } while(!ary_size);
301                         op->line = realloc(op->line, ary_size * sizeof(char *));
302                         op->lens = realloc(op->lens, ary_size * sizeof(size_t));
303                 }
305                 /* set the pointer to the string */
306                 op->line[lineno] = &buf[i];
308                 /* hop to next newline or end of buffer */
309                 while(buf[i] != '\n' && i < op->buflen) i++;
310                 buf[i] = '\0';
312                 /* calculate the string length using pointer difference */
313                 op->lens[lineno] = (size_t)&buf[i] - (size_t)op->line[lineno];
315                 lineno++;
316                 i++;
317         }
319         return lineno;
323 int
324 np_runcmd(const char *cmd, output *out, output *err, int flags)
326         int fd, pfd_out[2], pfd_err[2];
328         /* initialize the structs */
329         if(out) memset(out, 0, sizeof(output));
330         if(err) memset(err, 0, sizeof(output));
332         if((fd = np_runcmd_open(cmd, pfd_out, pfd_err)) == -1)
333                 die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd);
335         if(out) out->lines = np_fetch_output(pfd_out[0], out, flags);
336         if(err) err->lines = np_fetch_output(pfd_err[0], err, flags);
338         return np_runcmd_close(fd);