Code

Removed debug line
[nagiosplug.git] / plugins / popen.c
1 /****************************************************************************
2  *
3  * Nagios plugins popen
4  *
5  * License: GPL
6  * Copyright (c) 2005 nagios-plugins team
7  *
8  * Last Modified: $Date$
9  *
10  * Description:
11  *
12  * A safe alternative to popen
13  * 
14  * Provides spopen and spclose
15  *
16  * FILE * spopen(const char *);
17  * int spclose(FILE *);
18  *
19  *
20  * Code taken with liitle modification from "Advanced Programming for the Unix
21  * Environment" by W. Richard Stevens
22  *
23  * This is considered safe in that no shell is spawned, and the environment and
24  * path passed to the exec'd program are esstially empty. (popen create a shell
25  * and passes the environment to it).
26  *
27  * License Information:
28  *
29  * This program is free software; you can redistribute it and/or modify
30  * it under the terms of the GNU General Public License as published by
31  * the Free Software Foundation; either version 2 of the License, or
32  * (at your option) any later version.
33  *
34  * This program is distributed in the hope that it will be useful,
35  * but WITHOUT ANY WARRANTY; without even the implied warranty of
36  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37  * GNU General Public License for more details.
38  *
39  * You should have received a copy of the GNU General Public License
40  * along with this program; if not, write to the Free Software
41  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 
42  *
43  * $Id$
44  *
45  ******************************************************************************/
47 #include "common.h"
49 /* extern so plugin has pid to kill exec'd process on timeouts */
50 extern int timeout_interval;
51 extern pid_t *childpid;
52 extern int *child_stderr_array;
53 extern FILE *child_process;
55 FILE *spopen (const char *);
56 int spclose (FILE *);
57 #ifdef REDHAT_SPOPEN_ERROR
58 RETSIGTYPE popen_sigchld_handler (int);
59 #endif
60 RETSIGTYPE popen_timeout_alarm_handler (int);
62 #include <stdarg.h>                                                     /* ANSI C header file */
63 #include <fcntl.h>
65 #include <limits.h>
66 #include <sys/resource.h>
68 #ifdef HAVE_SYS_WAIT_H
69 #include <sys/wait.h>
70 #endif
72 #ifndef WEXITSTATUS
73 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
74 #endif
76 #ifndef WIFEXITED
77 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
78 #endif
80 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
81 #if defined(SIG_IGN) && !defined(SIG_ERR)
82 #define SIG_ERR ((Sigfunc *)-1)
83 #endif
85 #define min(a,b)        ((a) < (b) ? (a) : (b))
86 #define max(a,b)        ((a) > (b) ? (a) : (b))
87 int open_max (void);                                            /* {Prog openmax} */
88 static void err_sys (const char *, ...) __attribute__((noreturn,format(printf, 1, 2)));
89 char *rtrim (char *, const char *);
91 char *pname = NULL;                                                     /* caller can set this from argv[0] */
93 /*int *childerr = NULL;*//* ptr to array allocated at run-time */
94 /*extern pid_t *childpid = NULL; *//* ptr to array allocated at run-time */
95 static int maxfd;                                                               /* from our open_max(), {Prog openmax} */
97 #ifdef REDHAT_SPOPEN_ERROR
98 static volatile int childtermd = 0;
99 #endif
101 FILE *
102 spopen (const char *cmdstring)
104         char *env[2];
105         char *cmd = NULL;
106         char **argv = NULL;
107         char *str, *tmp;
108         int argc;
110         int i = 0, pfd[2], pfderr[2];
111         pid_t pid;
113 #ifdef  RLIMIT_CORE
114         /* do not leave core files */
115         struct rlimit limit;
116         getrlimit (RLIMIT_CORE, &limit);
117         limit.rlim_cur = 0;
118         setrlimit (RLIMIT_CORE, &limit);
119 #endif
121         env[0] = strdup("LC_ALL=C");
122         env[1] = '\0';
124         /* if no command was passed, return with no error */
125         if (cmdstring == NULL)
126                 return (NULL);
128         /* make copy of command string so strtok() doesn't silently modify it */
129         /* (the calling program may want to access it later) */
130         cmd = malloc (strlen (cmdstring) + 1);
131         if (cmd == NULL)
132                 return NULL;
133         strcpy (cmd, cmdstring);
135         /* This is not a shell, so we don't handle "???" */
136         if (strstr (cmdstring, "\""))
137                 return NULL;
139         /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
140         if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
141                 return NULL;
143         /* there cannot be more args than characters */
144         argc = strlen (cmdstring) + 1;  /* add 1 for NULL termination */
145         argv = malloc (sizeof(char*)*argc);
146         
147         if (argv == NULL) {
148                 printf ("%s\n", _("Could not malloc argv array in popen()"));
149                 return NULL;
150         }
152         /* loop to get arguments to command */
153         while (cmd) {
154                 str = cmd;
155                 str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
157                 if (i >= argc - 2) {
158                         printf ("%s\n",_("CRITICAL - You need more args!!!"));
159                         return (NULL);
160                 }
162                 if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
163                         str++;
164                         if (!strstr (str, "'"))
165                                 return NULL;                                            /* balanced? */
166                         cmd = 1 + strstr (str, "'");
167                         str[strcspn (str, "'")] = 0;
168                 }
169                 else if (strcspn(str,"'") < strcspn (str, " \t\r\n")) {
170                                                                                 /* handle --option='foo bar' strings */
171                         tmp = str + strcspn(str, "'") + 1; 
172                         if (!strstr (tmp, "'"))
173                                 return NULL;                                            /* balanced? */
174                         tmp += strcspn(tmp,"'") + 1;
175                         *tmp = 0;
176                         cmd = tmp + 1;
177                 } else {
178                         if (strpbrk (str, " \t\r\n")) {
179                                 cmd = 1 + strpbrk (str, " \t\r\n");
180                                 str[strcspn (str, " \t\r\n")] = 0;
181                         }
182                         else {
183                                 cmd = NULL;
184                         }
185                 }
187                 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
188                         cmd = NULL;
190                 argv[i++] = str;
192         }
193         argv[i] = NULL;
195         if (childpid == NULL) {                         /* first time through */
196                 maxfd = open_max ();                            /* allocate zeroed out array for child pids */
197                 if ((childpid = calloc ((size_t)maxfd, sizeof (pid_t))) == NULL)
198                         return (NULL);
199         }
201         if (child_stderr_array == NULL) {       /* first time through */
202                 maxfd = open_max ();                            /* allocate zeroed out array for child pids */
203                 if ((child_stderr_array = calloc ((size_t)maxfd, sizeof (int))) == NULL)
204                         return (NULL);
205         }
207         if (pipe (pfd) < 0)
208                 return (NULL);                                                  /* errno set by pipe() */
210         if (pipe (pfderr) < 0)
211                 return (NULL);                                                  /* errno set by pipe() */
213 #ifdef REDHAT_SPOPEN_ERROR
214         if (signal (SIGCHLD, popen_sigchld_handler) == SIG_ERR) {
215                 usage4 (_("Cannot catch SIGCHLD"));
216         }
217 #endif
219         if ((pid = fork ()) < 0)
220                 return (NULL);                                                  /* errno set by fork() */
221         else if (pid == 0) {                                    /* child */
222                 close (pfd[0]);
223                 if (pfd[1] != STDOUT_FILENO) {
224                         dup2 (pfd[1], STDOUT_FILENO);
225                         close (pfd[1]);
226                 }
227                 close (pfderr[0]);
228                 if (pfderr[1] != STDERR_FILENO) {
229                         dup2 (pfderr[1], STDERR_FILENO);
230                         close (pfderr[1]);
231                 }
232                 /* close all descriptors in childpid[] */
233                 for (i = 0; i < maxfd; i++)
234                         if (childpid[i] > 0)
235                                 close (i);
237                 execve (argv[0], argv, env);
238                 _exit (0);
239         }
241         close (pfd[1]);                                                         /* parent */
242         if ((child_process = fdopen (pfd[0], "r")) == NULL)
243                 return (NULL);
244         close (pfderr[1]);
246         childpid[fileno (child_process)] = pid; /* remember child pid for this fd */
247         child_stderr_array[fileno (child_process)] = pfderr[0]; /* remember STDERR */
248         return (child_process);
251 int
252 spclose (FILE * fp)
254         int fd, status;
255         pid_t pid;
257         if (childpid == NULL)
258                 return (1);                                                             /* popen() has never been called */
260         fd = fileno (fp);
261         if ((pid = childpid[fd]) == 0)
262                 return (1);                                                             /* fp wasn't opened by popen() */
264         childpid[fd] = 0;
265         if (fclose (fp) == EOF)
266                 return (1);
268 #ifdef REDHAT_SPOPEN_ERROR
269         while (!childtermd);                                                            /* wait until SIGCHLD */
270 #endif
272         while (waitpid (pid, &status, 0) < 0)
273                 if (errno != EINTR)
274                         return (1);                                                     /* error other than EINTR from waitpid() */
276         if (WIFEXITED (status))
277                 return (WEXITSTATUS (status));  /* return child's termination status */
279         return (1);
282 #ifdef  OPEN_MAX
283 static int openmax = OPEN_MAX;
284 #else
285 static int openmax = 0;
286 #endif
288 #define OPEN_MAX_GUESS  256                     /* if OPEN_MAX is indeterminate */
289                                 /* no guarantee this is adequate */
291 #ifdef REDHAT_SPOPEN_ERROR
292 RETSIGTYPE
293 popen_sigchld_handler (int signo)
295         if (signo == SIGCHLD)
296                 childtermd = 1;
298 #endif
300 RETSIGTYPE
301 popen_timeout_alarm_handler (int signo)
303         int fh;
304         if (signo == SIGALRM) {
305                 if (child_process != NULL) {
306                         fh=fileno (child_process);
307                         if(fh >= 0){
308                                 kill (childpid[fh], SIGKILL);
309                         }
310                         printf (_("CRITICAL - Plugin timed out after %d seconds\n"),
311                                                 timeout_interval);
312                 } else {
313                         printf ("%s\n", _("CRITICAL - popen timeout received, but no child process"));
314                 }
315                 exit (STATE_CRITICAL);
316         }
320 int
321 open_max (void)
323         if (openmax == 0) {                                             /* first time through */
324                 errno = 0;
325                 if ((openmax = sysconf (_SC_OPEN_MAX)) < 0) {
326                         if (errno == 0)
327                                 openmax = OPEN_MAX_GUESS;       /* it's indeterminate */
328                         else
329                                 err_sys (_("sysconf error for _SC_OPEN_MAX"));
330                 }
331         }
332         return (openmax);
336 /* Fatal error related to a system call.
337  * Print a message and die. */
339 #define MAXLINE 2048
340 static void
341 err_sys (const char *fmt, ...)
343         int errnoflag = 1;
344         int errno_save;
345         char buf[MAXLINE];
347         va_list ap;
349         va_start (ap, fmt);
350         /* err_doit (1, fmt, ap); */
351         errno_save = errno;                                             /* value caller might want printed */
352         vsprintf (buf, fmt, ap);
353         if (errnoflag)
354                 sprintf (buf + strlen (buf), ": %s", strerror (errno_save));
355         strcat (buf, "\n");
356         fflush (stdout);                                                        /* in case stdout and stderr are the same */
357         fputs (buf, stderr);
358         fflush (NULL);                                                          /* flushes all stdio output streams */
359         va_end (ap);
360         exit (1);
363 char *
364 rtrim (char *str, const char *tok)
366         int i = 0;
367         int j = sizeof (str);
369         while (str != NULL && i < j) {
370                 if (*(str + i) == *tok) {
371                         sprintf (str + i, "%s", "\0");
372                         return str;
373                 }
374                 i++;
375         }
376         return str;