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);
115 if (argv == NULL) {
116 printf ("Could not malloc argv array in popen()\n");
117 return NULL;
118 }
120 /* loop to get arguments to command */
121 while (cmd) {
122 str = cmd;
123 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
125 if (i >= argc - 2) {
126 printf ("CRITICAL - You need more args!!!\n");
127 return (NULL);
128 }
130 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
131 str++;
132 if (!strstr (str, "'"))
133 return NULL; /* balanced? */
134 cmd = 1 + strstr (str, "'");
135 str[strcspn (str, "'")] = 0;
136 }
137 else {
138 if (strpbrk (str, " \t\r\n")) {
139 cmd = 1 + strpbrk (str, " \t\r\n");
140 str[strcspn (str, " \t\r\n")] = 0;
141 }
142 else {
143 cmd = NULL;
144 }
145 }
147 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
148 cmd = NULL;
150 argv[i++] = str;
152 }
153 argv[i] = NULL;
155 if (childpid == NULL) { /* first time through */
156 maxfd = open_max (); /* allocate zeroed out array for child pids */
157 if ((childpid = calloc ((size_t)maxfd, sizeof (pid_t))) == NULL)
158 return (NULL);
159 }
161 if (child_stderr_array == NULL) { /* first time through */
162 maxfd = open_max (); /* allocate zeroed out array for child pids */
163 if ((child_stderr_array = calloc ((size_t)maxfd, sizeof (int))) == NULL)
164 return (NULL);
165 }
167 if (pipe (pfd) < 0)
168 return (NULL); /* errno set by pipe() */
170 if (pipe (pfderr) < 0)
171 return (NULL); /* errno set by pipe() */
173 if ((pid = fork ()) < 0)
174 return (NULL); /* errno set by fork() */
175 else if (pid == 0) { /* child */
176 close (pfd[0]);
177 if (pfd[1] != STDOUT_FILENO) {
178 dup2 (pfd[1], STDOUT_FILENO);
179 close (pfd[1]);
180 }
181 close (pfderr[0]);
182 if (pfderr[1] != STDERR_FILENO) {
183 dup2 (pfderr[1], STDERR_FILENO);
184 close (pfderr[1]);
185 }
186 /* close all descriptors in childpid[] */
187 for (i = 0; i < maxfd; i++)
188 if (childpid[i] > 0)
189 close (i);
191 execve (argv[0], argv, env);
192 _exit (0);
193 }
195 close (pfd[1]); /* parent */
196 if ((child_process = fdopen (pfd[0], "r")) == NULL)
197 return (NULL);
198 close (pfderr[1]);
200 childpid[fileno (child_process)] = pid; /* remember child pid for this fd */
201 child_stderr_array[fileno (child_process)] = pfderr[0]; /* remember STDERR */
202 return (child_process);
203 }
205 int
206 spclose (FILE * fp)
207 {
208 int fd, status;
209 pid_t pid;
211 if (childpid == NULL)
212 return (1); /* popen() has never been called */
214 fd = fileno (fp);
215 if ((pid = childpid[fd]) == 0)
216 return (1); /* fp wasn't opened by popen() */
218 childpid[fd] = 0;
219 if (fclose (fp) == EOF)
220 return (1);
222 while (waitpid (pid, &status, 0) < 0)
223 if (errno != EINTR)
224 return (1); /* error other than EINTR from waitpid() */
226 if (WIFEXITED (status))
227 return (WEXITSTATUS (status)); /* return child's termination status */
229 return (1);
230 }
232 #ifdef OPEN_MAX
233 static int openmax = OPEN_MAX;
234 #else
235 static int openmax = 0;
236 #endif
238 #define OPEN_MAX_GUESS 256 /* if OPEN_MAX is indeterminate */
239 /* no guarantee this is adequate */
241 void
242 popen_timeout_alarm_handler (int signo)
243 {
244 if (signo == SIGALRM) {
245 kill (childpid[fileno (child_process)], SIGKILL);
246 printf ("CRITICAL - Plugin timed out after %d seconds\n",
247 timeout_interval);
248 exit (STATE_CRITICAL);
249 }
250 }
252 int
253 open_max (void)
254 {
255 if (openmax == 0) { /* first time through */
256 errno = 0;
257 if ((openmax = sysconf (_SC_OPEN_MAX)) < 0) {
258 if (errno == 0)
259 openmax = OPEN_MAX_GUESS; /* it's indeterminate */
260 else
261 err_sys ("sysconf error for _SC_OPEN_MAX");
262 }
263 }
264 return (openmax);
265 }
269 /* Fatal error related to a system call.
270 * Print a message and die. */
272 #define MAXLINE 2048
273 static void
274 err_sys (const char *fmt, ...)
275 {
276 int errnoflag = 1;
277 int errno_save;
278 char buf[MAXLINE];
280 va_list ap;
282 va_start (ap, fmt);
283 /* err_doit (1, fmt, ap); */
284 errno_save = errno; /* value caller might want printed */
285 vsprintf (buf, fmt, ap);
286 if (errnoflag)
287 sprintf (buf + strlen (buf), ": %s", strerror (errno_save));
288 strcat (buf, "\n");
289 fflush (stdout); /* in case stdout and stderr are the same */
290 fputs (buf, stderr);
291 fflush (NULL); /* flushes all stdio output streams */
292 va_end (ap);
293 exit (1);
294 }
296 char *
297 rtrim (char *str, const char *tok)
298 {
299 int i = 0;
300 int j = sizeof (str);
302 while (str != NULL && i < j) {
303 if (*(str + i) == *tok) {
304 sprintf (str + i, "%s", "\0");
305 return str;
306 }
307 i++;
308 }
309 return str;
310 }