Code

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