Sync with gnulib
[monitoring-plugins.git] / plugins / popen.c
blob716bd524042c54b99ed2f69034436a62340e28de
1 /*****************************************************************************
2 *
3 * Nagios plugins popen
4 *
5 * License: GPL
6 * Copyright (c) 2005-2007 Nagios Plugins Development Team
7 *
8 * Description:
9 *
10 * A safe alternative to popen
12 * Provides spopen and spclose
14 * FILE * spopen(const char *);
15 * int spclose(FILE *);
17 * Code taken with liitle modification from "Advanced Programming for the Unix
18 * Environment" by W. Richard Stevens
20 * This is considered safe in that no shell is spawned, and the environment
21 * and path passed to the exec'd program are essentially empty. (popen create
22 * a shell and passes the environment to it).
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.
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.
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/>.
39 *****************************************************************************/
41 #include "common.h"
43 /* extern so plugin has pid to kill exec'd process on timeouts */
44 extern int timeout_interval;
45 extern pid_t *childpid;
46 extern int *child_stderr_array;
47 extern FILE *child_process;
49 FILE *spopen (const char *);
50 int spclose (FILE *);
51 #ifdef REDHAT_SPOPEN_ERROR
52 RETSIGTYPE popen_sigchld_handler (int);
53 #endif
54 RETSIGTYPE popen_timeout_alarm_handler (int);
56 #include <stdarg.h> /* ANSI C header file */
57 #include <fcntl.h>
59 #include <limits.h>
60 #include <sys/resource.h>
62 #ifdef HAVE_SYS_WAIT_H
63 #include <sys/wait.h>
64 #endif
66 #ifndef WEXITSTATUS
67 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
68 #endif
70 #ifndef WIFEXITED
71 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
72 #endif
74 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
75 #if defined(SIG_IGN) && !defined(SIG_ERR)
76 #define SIG_ERR ((Sigfunc *)-1)
77 #endif
79 #define min(a,b) ((a) < (b) ? (a) : (b))
80 #define max(a,b) ((a) > (b) ? (a) : (b))
81 int open_max (void); /* {Prog openmax} */
82 static void err_sys (const char *, ...) __attribute__((noreturn,format(printf, 1, 2)));
83 char *rtrim (char *, const char *);
85 char *pname = NULL; /* caller can set this from argv[0] */
87 /*int *childerr = NULL;*//* ptr to array allocated at run-time */
88 /*extern pid_t *childpid = NULL; *//* ptr to array allocated at run-time */
89 static int maxfd; /* from our open_max(), {Prog openmax} */
91 #ifdef REDHAT_SPOPEN_ERROR
92 static volatile int childtermd = 0;
93 #endif
95 FILE *
96 spopen (const char *cmdstring)
98 char *env[2];
99 char *cmd = NULL;
100 char **argv = NULL;
101 char *str, *tmp;
102 int argc;
104 int i = 0, pfd[2], pfderr[2];
105 pid_t pid;
107 #ifdef RLIMIT_CORE
108 /* do not leave core files */
109 struct rlimit limit;
110 getrlimit (RLIMIT_CORE, &limit);
111 limit.rlim_cur = 0;
112 setrlimit (RLIMIT_CORE, &limit);
113 #endif
115 env[0] = strdup("LC_ALL=C");
116 env[1] = '\0';
118 /* if no command was passed, return with no error */
119 if (cmdstring == NULL)
120 return (NULL);
122 /* make copy of command string so strtok() doesn't silently modify it */
123 /* (the calling program may want to access it later) */
124 cmd = malloc (strlen (cmdstring) + 1);
125 if (cmd == NULL)
126 return NULL;
127 strcpy (cmd, cmdstring);
129 /* This is not a shell, so we don't handle "???" */
130 if (strstr (cmdstring, "\""))
131 return NULL;
133 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
134 if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
135 return NULL;
137 /* there cannot be more args than characters */
138 argc = strlen (cmdstring) + 1; /* add 1 for NULL termination */
139 argv = malloc (sizeof(char*)*argc);
141 if (argv == NULL) {
142 printf ("%s\n", _("Could not malloc argv array in popen()"));
143 return NULL;
146 /* loop to get arguments to command */
147 while (cmd) {
148 str = cmd;
149 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
151 if (i >= argc - 2) {
152 printf ("%s\n",_("CRITICAL - You need more args!!!"));
153 return (NULL);
156 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
157 str++;
158 if (!strstr (str, "'"))
159 return NULL; /* balanced? */
160 cmd = 1 + strstr (str, "'");
161 str[strcspn (str, "'")] = 0;
163 else if (strcspn(str,"'") < strcspn (str, " \t\r\n")) {
164 /* handle --option='foo bar' strings */
165 tmp = str + strcspn(str, "'") + 1;
166 if (!strstr (tmp, "'"))
167 return NULL; /* balanced? */
168 tmp += strcspn(tmp,"'") + 1;
169 *tmp = 0;
170 cmd = tmp + 1;
171 } else {
172 if (strpbrk (str, " \t\r\n")) {
173 cmd = 1 + strpbrk (str, " \t\r\n");
174 str[strcspn (str, " \t\r\n")] = 0;
176 else {
177 cmd = NULL;
181 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
182 cmd = NULL;
184 argv[i++] = str;
187 argv[i] = NULL;
189 if (childpid == NULL) { /* first time through */
190 maxfd = open_max (); /* allocate zeroed out array for child pids */
191 if ((childpid = calloc ((size_t)maxfd, sizeof (pid_t))) == NULL)
192 return (NULL);
195 if (child_stderr_array == NULL) { /* first time through */
196 maxfd = open_max (); /* allocate zeroed out array for child pids */
197 if ((child_stderr_array = calloc ((size_t)maxfd, sizeof (int))) == NULL)
198 return (NULL);
201 if (pipe (pfd) < 0)
202 return (NULL); /* errno set by pipe() */
204 if (pipe (pfderr) < 0)
205 return (NULL); /* errno set by pipe() */
207 #ifdef REDHAT_SPOPEN_ERROR
208 if (signal (SIGCHLD, popen_sigchld_handler) == SIG_ERR) {
209 usage4 (_("Cannot catch SIGCHLD"));
211 #endif
213 if ((pid = fork ()) < 0)
214 return (NULL); /* errno set by fork() */
215 else if (pid == 0) { /* child */
216 close (pfd[0]);
217 if (pfd[1] != STDOUT_FILENO) {
218 dup2 (pfd[1], STDOUT_FILENO);
219 close (pfd[1]);
221 close (pfderr[0]);
222 if (pfderr[1] != STDERR_FILENO) {
223 dup2 (pfderr[1], STDERR_FILENO);
224 close (pfderr[1]);
226 /* close all descriptors in childpid[] */
227 for (i = 0; i < maxfd; i++)
228 if (childpid[i] > 0)
229 close (i);
231 execve (argv[0], argv, env);
232 _exit (0);
235 close (pfd[1]); /* parent */
236 if ((child_process = fdopen (pfd[0], "r")) == NULL)
237 return (NULL);
238 close (pfderr[1]);
240 childpid[fileno (child_process)] = pid; /* remember child pid for this fd */
241 child_stderr_array[fileno (child_process)] = pfderr[0]; /* remember STDERR */
242 return (child_process);
246 spclose (FILE * fp)
248 int fd, status;
249 pid_t pid;
251 if (childpid == NULL)
252 return (1); /* popen() has never been called */
254 fd = fileno (fp);
255 if ((pid = childpid[fd]) == 0)
256 return (1); /* fp wasn't opened by popen() */
258 childpid[fd] = 0;
259 if (fclose (fp) == EOF)
260 return (1);
262 #ifdef REDHAT_SPOPEN_ERROR
263 while (!childtermd); /* wait until SIGCHLD */
264 #endif
266 while (waitpid (pid, &status, 0) < 0)
267 if (errno != EINTR)
268 return (1); /* error other than EINTR from waitpid() */
270 if (WIFEXITED (status))
271 return (WEXITSTATUS (status)); /* return child's termination status */
273 return (1);
276 #ifdef OPEN_MAX
277 static int openmax = OPEN_MAX;
278 #else
279 static int openmax = 0;
280 #endif
282 #define OPEN_MAX_GUESS 256 /* if OPEN_MAX is indeterminate */
283 /* no guarantee this is adequate */
285 #ifdef REDHAT_SPOPEN_ERROR
286 RETSIGTYPE
287 popen_sigchld_handler (int signo)
289 if (signo == SIGCHLD)
290 childtermd = 1;
292 #endif
294 RETSIGTYPE
295 popen_timeout_alarm_handler (int signo)
297 int fh;
298 if (signo == SIGALRM) {
299 if (child_process != NULL) {
300 fh=fileno (child_process);
301 if(fh >= 0){
302 kill (childpid[fh], SIGKILL);
304 printf (_("CRITICAL - Plugin timed out after %d seconds\n"),
305 timeout_interval);
306 } else {
307 printf ("%s\n", _("CRITICAL - popen timeout received, but no child process"));
309 exit (STATE_CRITICAL);
315 open_max (void)
317 if (openmax == 0) { /* first time through */
318 errno = 0;
319 if ((openmax = sysconf (_SC_OPEN_MAX)) < 0) {
320 if (errno == 0)
321 openmax = OPEN_MAX_GUESS; /* it's indeterminate */
322 else
323 err_sys (_("sysconf error for _SC_OPEN_MAX"));
326 return (openmax);
330 /* Fatal error related to a system call.
331 * Print a message and die. */
333 #define MAXLINE 2048
334 static void
335 err_sys (const char *fmt, ...)
337 int errnoflag = 1;
338 int errno_save;
339 char buf[MAXLINE];
341 va_list ap;
343 va_start (ap, fmt);
344 /* err_doit (1, fmt, ap); */
345 errno_save = errno; /* value caller might want printed */
346 vsprintf (buf, fmt, ap);
347 if (errnoflag)
348 sprintf (buf + strlen (buf), ": %s", strerror (errno_save));
349 strcat (buf, "\n");
350 fflush (stdout); /* in case stdout and stderr are the same */
351 fputs (buf, stderr);
352 fflush (NULL); /* flushes all stdio output streams */
353 va_end (ap);
354 exit (1);
357 char *
358 rtrim (char *str, const char *tok)
360 int i = 0;
361 int j = sizeof (str);
363 while (str != NULL && i < j) {
364 if (*(str + i) == *tok) {
365 sprintf (str + i, "%s", "\0");
366 return str;
368 i++;
370 return str;