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