1 /*****************************************************************************
2 *
3 * Nagios plugins popen
4 *
5 * License: GPL
6 * Copyright (c) 2005-2007 Nagios Plugins Development Team
7 *
8 * Last Modified: $Date$
9 *
10 * Description:
11 *
12 * A safe alternative to popen
13 *
14 * Provides spopen and spclose
15 *
16 * FILE * spopen(const char *);
17 * int spclose(FILE *);
18 *
19 * Code taken with liitle modification from "Advanced Programming for the Unix
20 * Environment" by W. Richard Stevens
21 *
22 * This is considered safe in that no shell is spawned, and the environment
23 * and path passed to the exec'd program are essentially empty. (popen create
24 * a shell and passes the environment to it).
25 *
26 *
27 * This program is free software: you can redistribute it and/or modify
28 * it under the terms of the GNU General Public License as published by
29 * the Free Software Foundation, either version 3 of the License, or
30 * (at your option) any later version.
31 *
32 * This program is distributed in the hope that it will be useful,
33 * but WITHOUT ANY WARRANTY; without even the implied warranty of
34 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 * GNU General Public License for more details.
36 *
37 * You should have received a copy of the GNU General Public License
38 * along with this program. If not, see <http://www.gnu.org/licenses/>.
39 *
40 * $Id$
41 *
42 *****************************************************************************/
44 #include "common.h"
46 /* extern so plugin has pid to kill exec'd process on timeouts */
47 extern int timeout_interval;
48 extern pid_t *childpid;
49 extern int *child_stderr_array;
50 extern FILE *child_process;
52 FILE *spopen (const char *);
53 int spclose (FILE *);
54 #ifdef REDHAT_SPOPEN_ERROR
55 RETSIGTYPE popen_sigchld_handler (int);
56 #endif
57 RETSIGTYPE popen_timeout_alarm_handler (int);
59 #include <stdarg.h> /* ANSI C header file */
60 #include <fcntl.h>
62 #include <limits.h>
63 #include <sys/resource.h>
65 #ifdef HAVE_SYS_WAIT_H
66 #include <sys/wait.h>
67 #endif
69 #ifndef WEXITSTATUS
70 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
71 #endif
73 #ifndef WIFEXITED
74 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
75 #endif
77 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
78 #if defined(SIG_IGN) && !defined(SIG_ERR)
79 #define SIG_ERR ((Sigfunc *)-1)
80 #endif
82 #define min(a,b) ((a) < (b) ? (a) : (b))
83 #define max(a,b) ((a) > (b) ? (a) : (b))
84 int open_max (void); /* {Prog openmax} */
85 static void err_sys (const char *, ...) __attribute__((noreturn,format(printf, 1, 2)));
86 char *rtrim (char *, const char *);
88 char *pname = NULL; /* caller can set this from argv[0] */
90 /*int *childerr = NULL;*//* ptr to array allocated at run-time */
91 /*extern pid_t *childpid = NULL; *//* ptr to array allocated at run-time */
92 static int maxfd; /* from our open_max(), {Prog openmax} */
94 #ifdef REDHAT_SPOPEN_ERROR
95 static volatile int childtermd = 0;
96 #endif
98 FILE *
99 spopen (const char *cmdstring)
100 {
101 char *env[2];
102 char *cmd = NULL;
103 char **argv = NULL;
104 char *str, *tmp;
105 int argc;
107 int i = 0, pfd[2], pfderr[2];
108 pid_t pid;
110 #ifdef RLIMIT_CORE
111 /* do not leave core files */
112 struct rlimit limit;
113 getrlimit (RLIMIT_CORE, &limit);
114 limit.rlim_cur = 0;
115 setrlimit (RLIMIT_CORE, &limit);
116 #endif
118 env[0] = strdup("LC_ALL=C");
119 env[1] = '\0';
121 /* if no command was passed, return with no error */
122 if (cmdstring == NULL)
123 return (NULL);
125 /* make copy of command string so strtok() doesn't silently modify it */
126 /* (the calling program may want to access it later) */
127 cmd = malloc (strlen (cmdstring) + 1);
128 if (cmd == NULL)
129 return NULL;
130 strcpy (cmd, cmdstring);
132 /* This is not a shell, so we don't handle "???" */
133 if (strstr (cmdstring, "\""))
134 return NULL;
136 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
137 if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
138 return NULL;
140 /* there cannot be more args than characters */
141 argc = strlen (cmdstring) + 1; /* add 1 for NULL termination */
142 argv = malloc (sizeof(char*)*argc);
144 if (argv == NULL) {
145 printf ("%s\n", _("Could not malloc argv array in popen()"));
146 return NULL;
147 }
149 /* loop to get arguments to command */
150 while (cmd) {
151 str = cmd;
152 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
154 if (i >= argc - 2) {
155 printf ("%s\n",_("CRITICAL - You need more args!!!"));
156 return (NULL);
157 }
159 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
160 str++;
161 if (!strstr (str, "'"))
162 return NULL; /* balanced? */
163 cmd = 1 + strstr (str, "'");
164 str[strcspn (str, "'")] = 0;
165 }
166 else if (strcspn(str,"'") < strcspn (str, " \t\r\n")) {
167 /* handle --option='foo bar' strings */
168 tmp = str + strcspn(str, "'") + 1;
169 if (!strstr (tmp, "'"))
170 return NULL; /* balanced? */
171 tmp += strcspn(tmp,"'") + 1;
172 *tmp = 0;
173 cmd = tmp + 1;
174 } else {
175 if (strpbrk (str, " \t\r\n")) {
176 cmd = 1 + strpbrk (str, " \t\r\n");
177 str[strcspn (str, " \t\r\n")] = 0;
178 }
179 else {
180 cmd = NULL;
181 }
182 }
184 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
185 cmd = NULL;
187 argv[i++] = str;
189 }
190 argv[i] = NULL;
192 if (childpid == NULL) { /* first time through */
193 maxfd = open_max (); /* allocate zeroed out array for child pids */
194 if ((childpid = calloc ((size_t)maxfd, sizeof (pid_t))) == NULL)
195 return (NULL);
196 }
198 if (child_stderr_array == NULL) { /* first time through */
199 maxfd = open_max (); /* allocate zeroed out array for child pids */
200 if ((child_stderr_array = calloc ((size_t)maxfd, sizeof (int))) == NULL)
201 return (NULL);
202 }
204 if (pipe (pfd) < 0)
205 return (NULL); /* errno set by pipe() */
207 if (pipe (pfderr) < 0)
208 return (NULL); /* errno set by pipe() */
210 #ifdef REDHAT_SPOPEN_ERROR
211 if (signal (SIGCHLD, popen_sigchld_handler) == SIG_ERR) {
212 usage4 (_("Cannot catch SIGCHLD"));
213 }
214 #endif
216 if ((pid = fork ()) < 0)
217 return (NULL); /* errno set by fork() */
218 else if (pid == 0) { /* child */
219 close (pfd[0]);
220 if (pfd[1] != STDOUT_FILENO) {
221 dup2 (pfd[1], STDOUT_FILENO);
222 close (pfd[1]);
223 }
224 close (pfderr[0]);
225 if (pfderr[1] != STDERR_FILENO) {
226 dup2 (pfderr[1], STDERR_FILENO);
227 close (pfderr[1]);
228 }
229 /* close all descriptors in childpid[] */
230 for (i = 0; i < maxfd; i++)
231 if (childpid[i] > 0)
232 close (i);
234 execve (argv[0], argv, env);
235 _exit (0);
236 }
238 close (pfd[1]); /* parent */
239 if ((child_process = fdopen (pfd[0], "r")) == NULL)
240 return (NULL);
241 close (pfderr[1]);
243 childpid[fileno (child_process)] = pid; /* remember child pid for this fd */
244 child_stderr_array[fileno (child_process)] = pfderr[0]; /* remember STDERR */
245 return (child_process);
246 }
248 int
249 spclose (FILE * fp)
250 {
251 int fd, status;
252 pid_t pid;
254 if (childpid == NULL)
255 return (1); /* popen() has never been called */
257 fd = fileno (fp);
258 if ((pid = childpid[fd]) == 0)
259 return (1); /* fp wasn't opened by popen() */
261 childpid[fd] = 0;
262 if (fclose (fp) == EOF)
263 return (1);
265 #ifdef REDHAT_SPOPEN_ERROR
266 while (!childtermd); /* wait until SIGCHLD */
267 #endif
269 while (waitpid (pid, &status, 0) < 0)
270 if (errno != EINTR)
271 return (1); /* error other than EINTR from waitpid() */
273 if (WIFEXITED (status))
274 return (WEXITSTATUS (status)); /* return child's termination status */
276 return (1);
277 }
279 #ifdef OPEN_MAX
280 static int openmax = OPEN_MAX;
281 #else
282 static int openmax = 0;
283 #endif
285 #define OPEN_MAX_GUESS 256 /* if OPEN_MAX is indeterminate */
286 /* no guarantee this is adequate */
288 #ifdef REDHAT_SPOPEN_ERROR
289 RETSIGTYPE
290 popen_sigchld_handler (int signo)
291 {
292 if (signo == SIGCHLD)
293 childtermd = 1;
294 }
295 #endif
297 RETSIGTYPE
298 popen_timeout_alarm_handler (int signo)
299 {
300 int fh;
301 if (signo == SIGALRM) {
302 if (child_process != NULL) {
303 fh=fileno (child_process);
304 if(fh >= 0){
305 kill (childpid[fh], SIGKILL);
306 }
307 printf (_("CRITICAL - Plugin timed out after %d seconds\n"),
308 timeout_interval);
309 } else {
310 printf ("%s\n", _("CRITICAL - popen timeout received, but no child process"));
311 }
312 exit (STATE_CRITICAL);
313 }
314 }
317 int
318 open_max (void)
319 {
320 if (openmax == 0) { /* first time through */
321 errno = 0;
322 if ((openmax = sysconf (_SC_OPEN_MAX)) < 0) {
323 if (errno == 0)
324 openmax = OPEN_MAX_GUESS; /* it's indeterminate */
325 else
326 err_sys (_("sysconf error for _SC_OPEN_MAX"));
327 }
328 }
329 return (openmax);
330 }
333 /* Fatal error related to a system call.
334 * Print a message and die. */
336 #define MAXLINE 2048
337 static void
338 err_sys (const char *fmt, ...)
339 {
340 int errnoflag = 1;
341 int errno_save;
342 char buf[MAXLINE];
344 va_list ap;
346 va_start (ap, fmt);
347 /* err_doit (1, fmt, ap); */
348 errno_save = errno; /* value caller might want printed */
349 vsprintf (buf, fmt, ap);
350 if (errnoflag)
351 sprintf (buf + strlen (buf), ": %s", strerror (errno_save));
352 strcat (buf, "\n");
353 fflush (stdout); /* in case stdout and stderr are the same */
354 fputs (buf, stderr);
355 fflush (NULL); /* flushes all stdio output streams */
356 va_end (ap);
357 exit (1);
358 }
360 char *
361 rtrim (char *str, const char *tok)
362 {
363 int i = 0;
364 int j = sizeof (str);
366 while (str != NULL && i < j) {
367 if (*(str + i) == *tok) {
368 sprintf (str + i, "%s", "\0");
369 return str;
370 }
371 i++;
372 }
373 return str;
374 }