Back to index

nagios-plugins  1.4.16
runcmd.c
Go to the documentation of this file.
00001 /*****************************************************************************
00002 * 
00003 * Nagios run command utilities
00004 * 
00005 * License: GPL
00006 * Copyright (c) 2005-2006 Nagios Plugins Development Team
00007 * 
00008 * Description :
00009 * 
00010 * A simple interface to executing programs from other programs, using an
00011 * optimized and safe popen()-like implementation. It is considered safe
00012 * in that no shell needs to be spawned and the environment passed to the
00013 * execve()'d program is essentially empty.
00014 * 
00015 * The code in this file is a derivative of popen.c which in turn was taken
00016 * from "Advanced Programming for the Unix Environment" by W. Richard Stevens.
00017 * 
00018 * Care has been taken to make sure the functions are async-safe. The one
00019 * function which isn't is np_runcmd_init() which it doesn't make sense to
00020 * call twice anyway, so the api as a whole should be considered async-safe.
00021 * 
00022 * 
00023 * This program is free software: you can redistribute it and/or modify
00024 * it under the terms of the GNU General Public License as published by
00025 * the Free Software Foundation, either version 3 of the License, or
00026 * (at your option) any later version.
00027 * 
00028 * This program is distributed in the hope that it will be useful,
00029 * but WITHOUT ANY WARRANTY; without even the implied warranty of
00030 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00031 * GNU General Public License for more details.
00032 * 
00033 * You should have received a copy of the GNU General Public License
00034 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
00035 * 
00036 * 
00037 *****************************************************************************/
00038 
00039 #define NAGIOSPLUG_API_C 1
00040 
00042 #include "runcmd.h"
00043 #ifdef HAVE_SYS_WAIT_H
00044 # include <sys/wait.h>
00045 #endif
00046 
00048 #ifndef WEXITSTATUS
00049 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
00050 #endif
00051 
00052 #ifndef WIFEXITED
00053 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
00054 #endif
00055 
00056 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
00057 #if defined(SIG_IGN) && !defined(SIG_ERR)
00058 # define SIG_ERR ((Sigfunc *)-1)
00059 #endif
00060 
00061 /* This variable must be global, since there's no way the caller
00062  * can forcibly slay a dead or ungainly running program otherwise.
00063  * Multithreading apps and plugins can initialize it (via NP_RUNCMD_INIT)
00064  * in an async safe manner PRIOR to calling np_runcmd() for the first time.
00065  *
00066  * The check for initialized values is atomic and can
00067  * occur in any number of threads simultaneously. */
00068 static pid_t *np_pids = NULL;
00069 
00070 /* Try sysconf(_SC_OPEN_MAX) first, as it can be higher than OPEN_MAX.
00071  * If that fails and the macro isn't defined, we fall back to an educated
00072  * guess. There's no guarantee that our guess is adequate and the program
00073  * will die with SIGSEGV if it isn't and the upper boundary is breached. */
00074 #ifdef _SC_OPEN_MAX
00075 static long maxfd = 0;
00076 #elif defined(OPEN_MAX)
00077 # define maxfd OPEN_MAX
00078 #else /* sysconf macro unavailable, so guess (may be wildly inaccurate) */
00079 # define maxfd 256
00080 #endif
00081 
00082 
00084 static int np_runcmd_open(const char *, int *, int *)
00085        __attribute__((__nonnull__(1, 2, 3)));
00086 
00087 static int np_fetch_output(int, output *, int)
00088        __attribute__((__nonnull__(2)));
00089 
00090 static int np_runcmd_close(int);
00091 
00092 /* prototype imported from utils.h */
00093 extern void die (int, const char *, ...)
00094        __attribute__((__noreturn__,__format__(__printf__, 2, 3)));
00095 
00096 
00097 /* this function is NOT async-safe. It is exported so multithreaded
00098  * plugins (or other apps) can call it prior to running any commands
00099  * through this api and thus achieve async-safeness throughout the api */
00100 void np_runcmd_init(void)
00101 {
00102 #ifndef maxfd
00103        if(!maxfd && (maxfd = sysconf(_SC_OPEN_MAX)) < 0) {
00104               /* possibly log or emit a warning here, since there's no
00105                * guarantee that our guess at maxfd will be adequate */
00106               maxfd = 256;
00107        }
00108 #endif
00109 
00110        if(!np_pids) np_pids = calloc(maxfd, sizeof(pid_t));
00111 }
00112 
00113 
00114 /* Start running a command */
00115 static int
00116 np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr)
00117 {
00118        char *env[2];
00119        char *cmd = NULL;
00120        char **argv = NULL;
00121        char *str;
00122        int argc;
00123        size_t cmdlen;
00124        pid_t pid;
00125 #ifdef RLIMIT_CORE
00126        struct rlimit limit;
00127 #endif
00128 
00129        int i = 0;
00130 
00131        if(!np_pids) NP_RUNCMD_INIT;
00132 
00133        env[0] = strdup("LC_ALL=C");
00134        env[1] = '\0';
00135 
00136        /* if no command was passed, return with no error */
00137        if (cmdstring == NULL)
00138               return -1;
00139 
00140        /* make copy of command string so strtok() doesn't silently modify it */
00141        /* (the calling program may want to access it later) */
00142        cmdlen = strlen(cmdstring);
00143        if((cmd = malloc(cmdlen + 1)) == NULL) return -1;
00144        memcpy(cmd, cmdstring, cmdlen);
00145        cmd[cmdlen] = '\0';
00146 
00147        /* This is not a shell, so we don't handle "???" */
00148        if (strstr (cmdstring, "\"")) return -1;
00149 
00150        /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
00151        if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
00152               return -1;
00153 
00154        /* each arg must be whitespace-separated, so args can be a maximum
00155         * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
00156        argc = (cmdlen >> 1) + 2;
00157        argv = calloc(sizeof(char *), argc);
00158 
00159        if (argv == NULL) {
00160               printf ("%s\n", _("Could not malloc argv array in popen()"));
00161               return -1;
00162        }
00163 
00164        /* get command arguments (stupidly, but fairly quickly) */
00165        while (cmd) {
00166               str = cmd;
00167               str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
00168 
00169               if (strstr (str, "'") == str) {    /* handle SIMPLE quoted strings */
00170                      str++;
00171                      if (!strstr (str, "'")) return -1; /* balanced? */
00172                      cmd = 1 + strstr (str, "'");
00173                      str[strcspn (str, "'")] = 0;
00174               }
00175               else {
00176                      if (strpbrk (str, " \t\r\n")) {
00177                             cmd = 1 + strpbrk (str, " \t\r\n");
00178                             str[strcspn (str, " \t\r\n")] = 0;
00179                      }
00180                      else {
00181                             cmd = NULL;
00182                      }
00183               }
00184 
00185               if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
00186                      cmd = NULL;
00187 
00188               argv[i++] = str;
00189        }
00190 
00191        if (pipe(pfd) < 0 || pipe(pfderr) < 0 || (pid = fork()) < 0)
00192               return -1; /* errno set by the failing function */
00193 
00194        /* child runs exceve() and _exit. */
00195        if (pid == 0) {
00196 #ifdef        RLIMIT_CORE
00197               /* the program we execve shouldn't leave core files */
00198               getrlimit (RLIMIT_CORE, &limit);
00199               limit.rlim_cur = 0;
00200               setrlimit (RLIMIT_CORE, &limit);
00201 #endif
00202               close (pfd[0]);
00203               if (pfd[1] != STDOUT_FILENO) {
00204                      dup2 (pfd[1], STDOUT_FILENO);
00205                      close (pfd[1]);
00206               }
00207               close (pfderr[0]);
00208               if (pfderr[1] != STDERR_FILENO) {
00209                      dup2 (pfderr[1], STDERR_FILENO);
00210                      close (pfderr[1]);
00211               }
00212 
00213               /* close all descriptors in np_pids[]
00214                * This is executed in a separate address space (pure child),
00215                * so we don't have to worry about async safety */
00216               for (i = 0; i < maxfd; i++)
00217                      if(np_pids[i] > 0)
00218                             close (i);
00219 
00220               execve (argv[0], argv, env);
00221               _exit (STATE_UNKNOWN);
00222        }
00223 
00224        /* parent picks up execution here */
00225        /* close childs descriptors in our address space */
00226        close(pfd[1]);
00227        close(pfderr[1]);
00228 
00229        /* tag our file's entry in the pid-list and return it */
00230        np_pids[pfd[0]] = pid;
00231 
00232        return pfd[0];
00233 }
00234 
00235 
00236 static int
00237 np_runcmd_close(int fd)
00238 {
00239        int status;
00240        pid_t pid;
00241 
00242        /* make sure this fd was opened by popen() */
00243        if(fd < 0 || fd > maxfd || !np_pids || (pid = np_pids[fd]) == 0)
00244               return -1;
00245 
00246        np_pids[fd] = 0;
00247        if (close (fd) == -1) return -1;
00248 
00249        /* EINTR is ok (sort of), everything else is bad */
00250        while (waitpid (pid, &status, 0) < 0)
00251               if (errno != EINTR) return -1;
00252 
00253        /* return child's termination status */
00254        return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1;
00255 }
00256 
00257 
00258 void
00259 popen_timeout_alarm_handler (int signo)
00260 {
00261        size_t i;
00262 
00263        if (signo == SIGALRM)
00264               puts(_("CRITICAL - Plugin timed out while executing system call\n"));
00265 
00266        if(np_pids) for(i = 0; i < maxfd; i++) {
00267               if(np_pids[i] != 0) kill(np_pids[i], SIGKILL);
00268        }
00269 
00270        exit (STATE_CRITICAL);
00271 }
00272 
00273 
00274 static int
00275 np_fetch_output(int fd, output *op, int flags)
00276 {
00277        size_t len = 0, i = 0, lineno = 0;
00278        size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
00279        char *buf = NULL;
00280        int ret;
00281        char tmpbuf[4096];
00282 
00283        op->buf = NULL;
00284        op->buflen = 0;
00285        while((ret = read(fd, tmpbuf, sizeof(tmpbuf))) > 0) {
00286               len = (size_t)ret;
00287               op->buf = realloc(op->buf, op->buflen + len + 1);
00288               memcpy(op->buf + op->buflen, tmpbuf, len);
00289               op->buflen += len;
00290               i++;
00291        }
00292 
00293        if(ret < 0) {
00294               printf("read() returned %d: %s\n", ret, strerror(errno));
00295               return ret;
00296        }
00297 
00298        /* some plugins may want to keep output unbroken, and some commands
00299         * will yield no output, so return here for those */
00300        if(flags & RUNCMD_NO_ARRAYS || !op->buf || !op->buflen)
00301               return op->buflen;
00302 
00303        /* and some may want both */
00304        if(flags & RUNCMD_NO_ASSOC) {
00305               buf = malloc(op->buflen);
00306               memcpy(buf, op->buf, op->buflen);
00307        }
00308        else buf = op->buf;
00309 
00310        op->line = NULL;
00311        op->lens = NULL;
00312        i = 0;
00313        while(i < op->buflen) {
00314               /* make sure we have enough memory */
00315               if(lineno >= ary_size) {
00316                      /* ary_size must never be zero */
00317                      do {
00318                             ary_size = op->buflen >> --rsf;
00319                      } while(!ary_size);
00320 
00321                      op->line = realloc(op->line, ary_size * sizeof(char *));
00322                      op->lens = realloc(op->lens, ary_size * sizeof(size_t));
00323               }
00324 
00325               /* set the pointer to the string */
00326               op->line[lineno] = &buf[i];
00327 
00328               /* hop to next newline or end of buffer */
00329               while(buf[i] != '\n' && i < op->buflen) i++;
00330               buf[i] = '\0';
00331 
00332               /* calculate the string length using pointer difference */
00333               op->lens[lineno] = (size_t)&buf[i] - (size_t)op->line[lineno];
00334 
00335               lineno++;
00336               i++;
00337        }
00338 
00339        return lineno;
00340 }
00341 
00342 
00343 int
00344 np_runcmd(const char *cmd, output *out, output *err, int flags)
00345 {
00346        int fd, pfd_out[2], pfd_err[2];
00347 
00348        /* initialize the structs */
00349        if(out) memset(out, 0, sizeof(output));
00350        if(err) memset(err, 0, sizeof(output));
00351 
00352        if((fd = np_runcmd_open(cmd, pfd_out, pfd_err)) == -1)
00353               die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd);
00354 
00355        if(out) out->lines = np_fetch_output(pfd_out[0], out, flags);
00356        if(err) err->lines = np_fetch_output(pfd_err[0], err, flags);
00357 
00358        return np_runcmd_close(fd);
00359 }