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 RETSIGTYPE popen_timeout_alarm_handler (int);
35 #include <stdarg.h> /* ANSI C header file */
36 #include <fcntl.h>
38 #include <limits.h>
39 #include <sys/resource.h>
41 #ifdef HAVE_SYS_WAIT_H
42 #include <sys/wait.h>
43 #endif
45 #ifndef WEXITSTATUS
46 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
47 #endif
49 #ifndef WIFEXITED
50 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
51 #endif
53 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
54 #if defined(SIG_IGN) && !defined(SIG_ERR)
55 #define SIG_ERR ((Sigfunc *)-1)
56 #endif
58 #define min(a,b) ((a) < (b) ? (a) : (b))
59 #define max(a,b) ((a) > (b) ? (a) : (b))
60 int open_max (void); /* {Prog openmax} */
61 static void err_sys (const char *, ...) __attribute__((noreturn,format(printf, 1, 2)));
62 char *rtrim (char *, const char *);
64 char *pname = NULL; /* caller can set this from argv[0] */
66 /*int *childerr = NULL;*//* ptr to array allocated at run-time */
67 /*extern pid_t *childpid = NULL; *//* ptr to array allocated at run-time */
68 static int maxfd; /* from our open_max(), {Prog openmax} */
70 FILE *
71 spopen (const char *cmdstring)
72 {
73 char *env[2];
74 char *cmd = NULL;
75 char **argv = NULL;
76 char *str;
77 int argc;
79 int i = 0, pfd[2], pfderr[2];
80 pid_t pid;
82 #ifdef RLIMIT_CORE
83 /* do not leave core files */
84 struct rlimit limit;
85 getrlimit (RLIMIT_CORE, &limit);
86 limit.rlim_cur = 0;
87 setrlimit (RLIMIT_CORE, &limit);
88 #endif
90 env[0] = strdup("LC_ALL=C");
91 env[1] = '\0';
93 /* if no command was passed, return with no error */
94 if (cmdstring == NULL)
95 return (NULL);
97 /* make copy of command string so strtok() doesn't silently modify it */
98 /* (the calling program may want to access it later) */
99 cmd = malloc (strlen (cmdstring) + 1);
100 if (cmd == NULL)
101 return NULL;
102 strcpy (cmd, cmdstring);
104 /* This is not a shell, so we don't handle "???" */
105 if (strstr (cmdstring, "\""))
106 return NULL;
108 /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
109 if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
110 return NULL;
112 /* there cannot be more args than characters */
113 argc = strlen (cmdstring) + 1; /* add 1 for NULL termination */
114 argv = malloc (sizeof(char*)*argc);
116 if (argv == NULL) {
117 printf (_("Could not malloc argv array in popen()\n"));
118 return NULL;
119 }
121 /* loop to get arguments to command */
122 while (cmd) {
123 str = cmd;
124 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
126 if (i >= argc - 2) {
127 printf (_("CRITICAL - You need more args!!!\n"));
128 return (NULL);
129 }
131 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
132 str++;
133 if (!strstr (str, "'"))
134 return NULL; /* balanced? */
135 cmd = 1 + strstr (str, "'");
136 str[strcspn (str, "'")] = 0;
137 }
138 else {
139 if (strpbrk (str, " \t\r\n")) {
140 cmd = 1 + strpbrk (str, " \t\r\n");
141 str[strcspn (str, " \t\r\n")] = 0;
142 }
143 else {
144 cmd = NULL;
145 }
146 }
148 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
149 cmd = NULL;
151 argv[i++] = str;
153 }
154 argv[i] = NULL;
156 if (childpid == NULL) { /* first time through */
157 maxfd = open_max (); /* allocate zeroed out array for child pids */
158 if ((childpid = calloc ((size_t)maxfd, sizeof (pid_t))) == NULL)
159 return (NULL);
160 }
162 if (child_stderr_array == NULL) { /* first time through */
163 maxfd = open_max (); /* allocate zeroed out array for child pids */
164 if ((child_stderr_array = calloc ((size_t)maxfd, sizeof (int))) == NULL)
165 return (NULL);
166 }
168 if (pipe (pfd) < 0)
169 return (NULL); /* errno set by pipe() */
171 if (pipe (pfderr) < 0)
172 return (NULL); /* errno set by pipe() */
174 if ((pid = fork ()) < 0)
175 return (NULL); /* errno set by fork() */
176 else if (pid == 0) { /* child */
177 close (pfd[0]);
178 if (pfd[1] != STDOUT_FILENO) {
179 dup2 (pfd[1], STDOUT_FILENO);
180 close (pfd[1]);
181 }
182 close (pfderr[0]);
183 if (pfderr[1] != STDERR_FILENO) {
184 dup2 (pfderr[1], STDERR_FILENO);
185 close (pfderr[1]);
186 }
187 /* close all descriptors in childpid[] */
188 for (i = 0; i < maxfd; i++)
189 if (childpid[i] > 0)
190 close (i);
192 execve (argv[0], argv, env);
193 _exit (0);
194 }
196 close (pfd[1]); /* parent */
197 if ((child_process = fdopen (pfd[0], "r")) == NULL)
198 return (NULL);
199 close (pfderr[1]);
201 childpid[fileno (child_process)] = pid; /* remember child pid for this fd */
202 child_stderr_array[fileno (child_process)] = pfderr[0]; /* remember STDERR */
203 return (child_process);
204 }
206 int
207 spclose (FILE * fp)
208 {
209 int fd, status;
210 pid_t pid;
212 if (childpid == NULL)
213 return (1); /* popen() has never been called */
215 fd = fileno (fp);
216 if ((pid = childpid[fd]) == 0)
217 return (1); /* fp wasn't opened by popen() */
219 childpid[fd] = 0;
220 if (fclose (fp) == EOF)
221 return (1);
223 while (waitpid (pid, &status, 0) < 0)
224 if (errno != EINTR)
225 return (1); /* error other than EINTR from waitpid() */
227 if (WIFEXITED (status))
228 return (WEXITSTATUS (status)); /* return child's termination status */
230 return (1);
231 }
233 #ifdef OPEN_MAX
234 static int openmax = OPEN_MAX;
235 #else
236 static int openmax = 0;
237 #endif
239 #define OPEN_MAX_GUESS 256 /* if OPEN_MAX is indeterminate */
240 /* no guarantee this is adequate */
243 void
244 popen_timeout_alarm_handler (int signo)
245 {
246 int fh;
247 if (signo == SIGALRM) {
248 fh=fileno (child_process);
249 if(fh >= 0){
250 kill (childpid[fh], SIGKILL);
251 }
252 printf (_("CRITICAL - Plugin timed out after %d seconds\n"),
253 timeout_interval);
254 exit (STATE_CRITICAL);
255 }
256 }
259 int
260 open_max (void)
261 {
262 if (openmax == 0) { /* first time through */
263 errno = 0;
264 if ((openmax = sysconf (_SC_OPEN_MAX)) < 0) {
265 if (errno == 0)
266 openmax = OPEN_MAX_GUESS; /* it's indeterminate */
267 else
268 err_sys (_("sysconf error for _SC_OPEN_MAX"));
269 }
270 }
271 return (openmax);
272 }
275 /* Fatal error related to a system call.
276 * Print a message and die. */
278 #define MAXLINE 2048
279 static void
280 err_sys (const char *fmt, ...)
281 {
282 int errnoflag = 1;
283 int errno_save;
284 char buf[MAXLINE];
286 va_list ap;
288 va_start (ap, fmt);
289 /* err_doit (1, fmt, ap); */
290 errno_save = errno; /* value caller might want printed */
291 vsprintf (buf, fmt, ap);
292 if (errnoflag)
293 sprintf (buf + strlen (buf), ": %s", strerror (errno_save));
294 strcat (buf, "\n");
295 fflush (stdout); /* in case stdout and stderr are the same */
296 fputs (buf, stderr);
297 fflush (NULL); /* flushes all stdio output streams */
298 va_end (ap);
299 exit (1);
300 }
302 char *
303 rtrim (char *str, const char *tok)
304 {
305 int i = 0;
306 int j = sizeof (str);
308 while (str != NULL && i < j) {
309 if (*(str + i) == *tok) {
310 sprintf (str + i, "%s", "\0");
311 return str;
312 }
313 i++;
314 }
315 return str;
316 }