1 /******************************************************************************
2 * popen.c
3 *
4 * A safe alternative to popen
5 *
6 * Provides spopen and spclose
8 FILE * spopen(const char *);
9 int spclose(FILE *);
11 *
12 * Code taken with liitle modification from "Advanced Programming for the Unix
13 * Environment" by W. Richard Stevens
14 *
15 * This is considered safe in that no shell is spawned, and the environment and
16 * path passed to the exec'd program are esstially empty. (popen create a shell
17 * and passes the environment to it).
18 *
19 * $Id$
20 *
21 ******************************************************************************/
23 #include "common.h"
25 /* extern so plugin has pid to kill exec'd process on timeouts */
26 extern int timeout_interval;
27 extern pid_t *childpid;
28 extern int *child_stderr_array;
29 extern FILE *child_process;
31 FILE *spopen (const char *);
32 int spclose (FILE *);
33 #ifdef REDHAT_SPOPEN_ERROR
34 RETSIGTYPE popen_sigchld_handler (int);
35 #endif
36 RETSIGTYPE popen_timeout_alarm_handler (int);
38 #include <stdarg.h> /* ANSI C header file */
39 #include <fcntl.h>
41 #include <limits.h>
42 #include <sys/resource.h>
44 #ifdef HAVE_SYS_WAIT_H
45 #include <sys/wait.h>
46 #endif
48 #ifndef WEXITSTATUS
49 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
50 #endif
52 #ifndef WIFEXITED
53 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
54 #endif
56 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
57 #if defined(SIG_IGN) && !defined(SIG_ERR)
58 #define SIG_ERR ((Sigfunc *)-1)
59 #endif
61 #define min(a,b) ((a) < (b) ? (a) : (b))
62 #define max(a,b) ((a) > (b) ? (a) : (b))
63 int open_max (void); /* {Prog openmax} */
64 static void err_sys (const char *, ...) __attribute__((noreturn,format(printf, 1, 2)));
65 char *rtrim (char *, const char *);
67 char *pname = NULL; /* caller can set this from argv[0] */
69 /*int *childerr = NULL;*//* ptr to array allocated at run-time */
70 /*extern pid_t *childpid = NULL; *//* ptr to array allocated at run-time */
71 static int maxfd; /* from our open_max(), {Prog openmax} */
73 #ifdef REDHAT_SPOPEN_ERROR
74 static volatile int childtermd = 0;
75 #endif
77 FILE *
78 spopen (const char *cmdstring)
79 {
80 char *env[2];
81 char *cmd = NULL;
82 char **argv = NULL;
83 char *str;
84 int argc;
86 int i = 0, pfd[2], pfderr[2];
87 pid_t pid;
89 #ifdef RLIMIT_CORE
90 /* do not leave core files */
91 struct rlimit limit;
92 getrlimit (RLIMIT_CORE, &limit);
93 limit.rlim_cur = 0;
94 setrlimit (RLIMIT_CORE, &limit);
95 #endif
97 env[0] = strdup("LC_ALL=C");
98 env[1] = '\0';
100 /* if no command was passed, return with no error */
101 if (cmdstring == NULL)
102 return (NULL);
104 /* make copy of command string so strtok() doesn't silently modify it */
105 /* (the calling program may want to access it later) */
106 cmd = malloc (strlen (cmdstring) + 1);
107 if (cmd == NULL)
108 return NULL;
109 strcpy (cmd, cmdstring);
111 /* This is not a shell, so we don't handle "???" */
112 if (strstr (cmdstring, "\""))
113 return NULL;
115 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
116 if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
117 return NULL;
119 /* there cannot be more args than characters */
120 argc = strlen (cmdstring) + 1; /* add 1 for NULL termination */
121 argv = malloc (sizeof(char*)*argc);
123 if (argv == NULL) {
124 printf (_("Could not malloc argv array in popen()\n"));
125 return NULL;
126 }
128 /* loop to get arguments to command */
129 while (cmd) {
130 str = cmd;
131 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
133 if (i >= argc - 2) {
134 printf (_("CRITICAL - You need more args!!!\n"));
135 return (NULL);
136 }
138 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
139 str++;
140 if (!strstr (str, "'"))
141 return NULL; /* balanced? */
142 cmd = 1 + strstr (str, "'");
143 str[strcspn (str, "'")] = 0;
144 }
145 else {
146 if (strpbrk (str, " \t\r\n")) {
147 cmd = 1 + strpbrk (str, " \t\r\n");
148 str[strcspn (str, " \t\r\n")] = 0;
149 }
150 else {
151 cmd = NULL;
152 }
153 }
155 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
156 cmd = NULL;
158 argv[i++] = str;
160 }
161 argv[i] = NULL;
163 if (childpid == NULL) { /* first time through */
164 maxfd = open_max (); /* allocate zeroed out array for child pids */
165 if ((childpid = calloc ((size_t)maxfd, sizeof (pid_t))) == NULL)
166 return (NULL);
167 }
169 if (child_stderr_array == NULL) { /* first time through */
170 maxfd = open_max (); /* allocate zeroed out array for child pids */
171 if ((child_stderr_array = calloc ((size_t)maxfd, sizeof (int))) == NULL)
172 return (NULL);
173 }
175 if (pipe (pfd) < 0)
176 return (NULL); /* errno set by pipe() */
178 if (pipe (pfderr) < 0)
179 return (NULL); /* errno set by pipe() */
181 #ifdef REDHAT_SPOPEN_ERROR
182 if (signal (SIGCHLD, popen_sigchld_handler) == SIG_ERR) {
183 usage4 (_("Cannot catch SIGCHLD"));
184 }
185 #endif
187 if ((pid = fork ()) < 0)
188 return (NULL); /* errno set by fork() */
189 else if (pid == 0) { /* child */
190 close (pfd[0]);
191 if (pfd[1] != STDOUT_FILENO) {
192 dup2 (pfd[1], STDOUT_FILENO);
193 close (pfd[1]);
194 }
195 close (pfderr[0]);
196 if (pfderr[1] != STDERR_FILENO) {
197 dup2 (pfderr[1], STDERR_FILENO);
198 close (pfderr[1]);
199 }
200 /* close all descriptors in childpid[] */
201 for (i = 0; i < maxfd; i++)
202 if (childpid[i] > 0)
203 close (i);
205 execve (argv[0], argv, env);
206 _exit (0);
207 }
209 close (pfd[1]); /* parent */
210 if ((child_process = fdopen (pfd[0], "r")) == NULL)
211 return (NULL);
212 close (pfderr[1]);
214 childpid[fileno (child_process)] = pid; /* remember child pid for this fd */
215 child_stderr_array[fileno (child_process)] = pfderr[0]; /* remember STDERR */
216 return (child_process);
217 }
219 int
220 spclose (FILE * fp)
221 {
222 int fd, status;
223 pid_t pid;
225 if (childpid == NULL)
226 return (1); /* popen() has never been called */
228 fd = fileno (fp);
229 if ((pid = childpid[fd]) == 0)
230 return (1); /* fp wasn't opened by popen() */
232 childpid[fd] = 0;
233 if (fclose (fp) == EOF)
234 return (1);
236 #ifdef REDHAT_SPOPEN_ERROR
237 while (!childtermd); /* wait until SIGCHLD */
238 #endif
240 while (waitpid (pid, &status, 0) < 0)
241 if (errno != EINTR)
242 return (1); /* error other than EINTR from waitpid() */
244 if (WIFEXITED (status))
245 return (WEXITSTATUS (status)); /* return child's termination status */
247 return (1);
248 }
250 #ifdef OPEN_MAX
251 static int openmax = OPEN_MAX;
252 #else
253 static int openmax = 0;
254 #endif
256 #define OPEN_MAX_GUESS 256 /* if OPEN_MAX is indeterminate */
257 /* no guarantee this is adequate */
259 #ifdef REDHAT_SPOPEN_ERROR
260 RETSIGTYPE
261 popen_sigchld_handler (int signo)
262 {
263 if (signo == SIGCHLD)
264 childtermd = 1;
265 }
266 #endif
268 RETSIGTYPE
269 popen_timeout_alarm_handler (int signo)
270 {
271 int fh;
272 if (signo == SIGALRM) {
273 fh=fileno (child_process);
274 if(fh >= 0){
275 kill (childpid[fh], SIGKILL);
276 }
277 printf (_("CRITICAL - Plugin timed out after %d seconds\n"),
278 timeout_interval);
279 exit (STATE_CRITICAL);
280 }
281 }
284 int
285 open_max (void)
286 {
287 if (openmax == 0) { /* first time through */
288 errno = 0;
289 if ((openmax = sysconf (_SC_OPEN_MAX)) < 0) {
290 if (errno == 0)
291 openmax = OPEN_MAX_GUESS; /* it's indeterminate */
292 else
293 err_sys (_("sysconf error for _SC_OPEN_MAX"));
294 }
295 }
296 return (openmax);
297 }
300 /* Fatal error related to a system call.
301 * Print a message and die. */
303 #define MAXLINE 2048
304 static void
305 err_sys (const char *fmt, ...)
306 {
307 int errnoflag = 1;
308 int errno_save;
309 char buf[MAXLINE];
311 va_list ap;
313 va_start (ap, fmt);
314 /* err_doit (1, fmt, ap); */
315 errno_save = errno; /* value caller might want printed */
316 vsprintf (buf, fmt, ap);
317 if (errnoflag)
318 sprintf (buf + strlen (buf), ": %s", strerror (errno_save));
319 strcat (buf, "\n");
320 fflush (stdout); /* in case stdout and stderr are the same */
321 fputs (buf, stderr);
322 fflush (NULL); /* flushes all stdio output streams */
323 va_end (ap);
324 exit (1);
325 }
327 char *
328 rtrim (char *str, const char *tok)
329 {
330 int i = 0;
331 int j = sizeof (str);
333 while (str != NULL && i < j) {
334 if (*(str + i) == *tok) {
335 sprintf (str + i, "%s", "\0");
336 return str;
337 }
338 i++;
339 }
340 return str;
341 }