Code

Fixed --help output (Ask Bjoern Hansen - #1714823)
[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;
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 {
170                         if (strpbrk (str, " \t\r\n")) {
171                                 cmd = 1 + strpbrk (str, " \t\r\n");
172                                 str[strcspn (str, " \t\r\n")] = 0;
173                         }
174                         else {
175                                 cmd = NULL;
176                         }
177                 }
179                 if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
180                         cmd = NULL;
182                 argv[i++] = str;
184         }
185         argv[i] = NULL;
187         if (childpid == NULL) {                         /* first time through */
188                 maxfd = open_max ();                            /* allocate zeroed out array for child pids */
189                 if ((childpid = calloc ((size_t)maxfd, sizeof (pid_t))) == NULL)
190                         return (NULL);
191         }
193         if (child_stderr_array == NULL) {       /* first time through */
194                 maxfd = open_max ();                            /* allocate zeroed out array for child pids */
195                 if ((child_stderr_array = calloc ((size_t)maxfd, sizeof (int))) == NULL)
196                         return (NULL);
197         }
199         if (pipe (pfd) < 0)
200                 return (NULL);                                                  /* errno set by pipe() */
202         if (pipe (pfderr) < 0)
203                 return (NULL);                                                  /* errno set by pipe() */
205 #ifdef REDHAT_SPOPEN_ERROR
206         if (signal (SIGCHLD, popen_sigchld_handler) == SIG_ERR) {
207                 usage4 (_("Cannot catch SIGCHLD"));
208         }
209 #endif
211         if ((pid = fork ()) < 0)
212                 return (NULL);                                                  /* errno set by fork() */
213         else if (pid == 0) {                                    /* child */
214                 close (pfd[0]);
215                 if (pfd[1] != STDOUT_FILENO) {
216                         dup2 (pfd[1], STDOUT_FILENO);
217                         close (pfd[1]);
218                 }
219                 close (pfderr[0]);
220                 if (pfderr[1] != STDERR_FILENO) {
221                         dup2 (pfderr[1], STDERR_FILENO);
222                         close (pfderr[1]);
223                 }
224                 /* close all descriptors in childpid[] */
225                 for (i = 0; i < maxfd; i++)
226                         if (childpid[i] > 0)
227                                 close (i);
229                 execve (argv[0], argv, env);
230                 _exit (0);
231         }
233         close (pfd[1]);                                                         /* parent */
234         if ((child_process = fdopen (pfd[0], "r")) == NULL)
235                 return (NULL);
236         close (pfderr[1]);
238         childpid[fileno (child_process)] = pid; /* remember child pid for this fd */
239         child_stderr_array[fileno (child_process)] = pfderr[0]; /* remember STDERR */
240         return (child_process);
243 int
244 spclose (FILE * fp)
246         int fd, status;
247         pid_t pid;
249         if (childpid == NULL)
250                 return (1);                                                             /* popen() has never been called */
252         fd = fileno (fp);
253         if ((pid = childpid[fd]) == 0)
254                 return (1);                                                             /* fp wasn't opened by popen() */
256         childpid[fd] = 0;
257         if (fclose (fp) == EOF)
258                 return (1);
260 #ifdef REDHAT_SPOPEN_ERROR
261         while (!childtermd);                                                            /* wait until SIGCHLD */
262 #endif
264         while (waitpid (pid, &status, 0) < 0)
265                 if (errno != EINTR)
266                         return (1);                                                     /* error other than EINTR from waitpid() */
268         if (WIFEXITED (status))
269                 return (WEXITSTATUS (status));  /* return child's termination status */
271         return (1);
274 #ifdef  OPEN_MAX
275 static int openmax = OPEN_MAX;
276 #else
277 static int openmax = 0;
278 #endif
280 #define OPEN_MAX_GUESS  256                     /* if OPEN_MAX is indeterminate */
281                                 /* no guarantee this is adequate */
283 #ifdef REDHAT_SPOPEN_ERROR
284 RETSIGTYPE
285 popen_sigchld_handler (int signo)
287         if (signo == SIGCHLD)
288                 childtermd = 1;
290 #endif
292 RETSIGTYPE
293 popen_timeout_alarm_handler (int signo)
295         int fh;
296         if (signo == SIGALRM) {
297                 if (child_process != NULL) {
298                         fh=fileno (child_process);
299                         if(fh >= 0){
300                                 kill (childpid[fh], SIGKILL);
301                         }
302                         printf (_("CRITICAL - Plugin timed out after %d seconds\n"),
303                                                 timeout_interval);
304                 } else {
305                         printf ("%s\n", _("CRITICAL - popen timeout received, but no child process"));
306                 }
307                 exit (STATE_CRITICAL);
308         }
312 int
313 open_max (void)
315         if (openmax == 0) {                                             /* first time through */
316                 errno = 0;
317                 if ((openmax = sysconf (_SC_OPEN_MAX)) < 0) {
318                         if (errno == 0)
319                                 openmax = OPEN_MAX_GUESS;       /* it's indeterminate */
320                         else
321                                 err_sys (_("sysconf error for _SC_OPEN_MAX"));
322                 }
323         }
324         return (openmax);
328 /* Fatal error related to a system call.
329  * Print a message and die. */
331 #define MAXLINE 2048
332 static void
333 err_sys (const char *fmt, ...)
335         int errnoflag = 1;
336         int errno_save;
337         char buf[MAXLINE];
339         va_list ap;
341         va_start (ap, fmt);
342         /* err_doit (1, fmt, ap); */
343         errno_save = errno;                                             /* value caller might want printed */
344         vsprintf (buf, fmt, ap);
345         if (errnoflag)
346                 sprintf (buf + strlen (buf), ": %s", strerror (errno_save));
347         strcat (buf, "\n");
348         fflush (stdout);                                                        /* in case stdout and stderr are the same */
349         fputs (buf, stderr);
350         fflush (NULL);                                                          /* flushes all stdio output streams */
351         va_end (ap);
352         exit (1);
355 char *
356 rtrim (char *str, const char *tok)
358         int i = 0;
359         int j = sizeof (str);
361         while (str != NULL && i < j) {
362                 if (*(str + i) == *tok) {
363                         sprintf (str + i, "%s", "\0");
364                         return str;
365                 }
366                 i++;
367         }
368         return str;