Back to index

nagios-plugins  1.4.16
utils_cmd.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 cmd_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 "common.h"
00043 #include "utils_cmd.h"
00044 #include "utils_base.h"
00045 #include <fcntl.h>
00046 
00047 #ifdef HAVE_SYS_WAIT_H
00048 # include <sys/wait.h>
00049 #endif
00050 
00051 /* used in _cmd_open to pass the environment to commands */
00052 extern char **environ;
00053 
00055 #ifndef WEXITSTATUS
00056 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
00057 #endif
00058 
00059 #ifndef WIFEXITED
00060 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
00061 #endif
00062 
00063 /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
00064 #if defined(SIG_IGN) && !defined(SIG_ERR)
00065 # define SIG_ERR ((Sigfunc *)-1)
00066 #endif
00067 
00068 /* This variable must be global, since there's no way the caller
00069  * can forcibly slay a dead or ungainly running program otherwise.
00070  * Multithreading apps and plugins can initialize it (via CMD_INIT)
00071  * in an async safe manner PRIOR to calling cmd_run() or cmd_run_array()
00072  * for the first time.
00073  *
00074  * The check for initialized values is atomic and can
00075  * occur in any number of threads simultaneously. */
00076 static pid_t *_cmd_pids = NULL;
00077 
00078 /* Try sysconf(_SC_OPEN_MAX) first, as it can be higher than OPEN_MAX.
00079  * If that fails and the macro isn't defined, we fall back to an educated
00080  * guess. There's no guarantee that our guess is adequate and the program
00081  * will die with SIGSEGV if it isn't and the upper boundary is breached. */
00082 #ifdef _SC_OPEN_MAX
00083 static long maxfd = 0;
00084 #elif defined(OPEN_MAX)
00085 # define maxfd OPEN_MAX
00086 #else  /* sysconf macro unavailable, so guess (may be wildly inaccurate) */
00087 # define maxfd 256
00088 #endif
00089 
00090 
00092 static int _cmd_open (char *const *, int *, int *)
00093        __attribute__ ((__nonnull__ (1, 2, 3)));
00094 
00095 static int _cmd_fetch_output (int, output *, int)
00096        __attribute__ ((__nonnull__ (2)));
00097 
00098 static int _cmd_close (int);
00099 
00100 /* prototype imported from utils.h */
00101 extern void die (int, const char *, ...)
00102        __attribute__ ((__noreturn__, __format__ (__printf__, 2, 3)));
00103 
00104 
00105 /* this function is NOT async-safe. It is exported so multithreaded
00106  * plugins (or other apps) can call it prior to running any commands
00107  * through this api and thus achieve async-safeness throughout the api */
00108 void
00109 cmd_init (void)
00110 {
00111 #ifndef maxfd
00112        if (!maxfd && (maxfd = sysconf (_SC_OPEN_MAX)) < 0) {
00113               /* possibly log or emit a warning here, since there's no
00114                * guarantee that our guess at maxfd will be adequate */
00115               maxfd = 256;
00116        }
00117 #endif
00118 
00119        if (!_cmd_pids)
00120               _cmd_pids = calloc (maxfd, sizeof (pid_t));
00121 }
00122 
00123 
00124 /* Start running a command, array style */
00125 static int
00126 _cmd_open (char *const *argv, int *pfd, int *pfderr)
00127 {
00128        pid_t pid;
00129 #ifdef RLIMIT_CORE
00130        struct rlimit limit;
00131 #endif
00132 
00133        int i = 0;
00134 
00135        /* if no command was passed, return with no error */
00136        if (argv == NULL)
00137               return -1;
00138 
00139        if (!_cmd_pids)
00140               CMD_INIT;
00141 
00142        setenv("LC_ALL", "C", 1);
00143 
00144        if (pipe (pfd) < 0 || pipe (pfderr) < 0 || (pid = fork ()) < 0)
00145               return -1;                                                            /* errno set by the failing function */
00146 
00147        /* child runs exceve() and _exit. */
00148        if (pid == 0) {
00149 #ifdef        RLIMIT_CORE
00150               /* the program we execve shouldn't leave core files */
00151               getrlimit (RLIMIT_CORE, &limit);
00152               limit.rlim_cur = 0;
00153               setrlimit (RLIMIT_CORE, &limit);
00154 #endif
00155               close (pfd[0]);
00156               if (pfd[1] != STDOUT_FILENO) {
00157                      dup2 (pfd[1], STDOUT_FILENO);
00158                      close (pfd[1]);
00159               }
00160               close (pfderr[0]);
00161               if (pfderr[1] != STDERR_FILENO) {
00162                      dup2 (pfderr[1], STDERR_FILENO);
00163                      close (pfderr[1]);
00164               }
00165 
00166               /* close all descriptors in _cmd_pids[]
00167                * This is executed in a separate address space (pure child),
00168                * so we don't have to worry about async safety */
00169               for (i = 0; i < maxfd; i++)
00170                      if (_cmd_pids[i] > 0)
00171                             close (i);
00172 
00173               execve (argv[0], argv, environ);
00174               _exit (STATE_UNKNOWN);
00175        }
00176 
00177        /* parent picks up execution here */
00178        /* close childs descriptors in our address space */
00179        close (pfd[1]);
00180        close (pfderr[1]);
00181 
00182        /* tag our file's entry in the pid-list and return it */
00183        _cmd_pids[pfd[0]] = pid;
00184 
00185        return pfd[0];
00186 }
00187 
00188 static int
00189 _cmd_close (int fd)
00190 {
00191        int status;
00192        pid_t pid;
00193 
00194        /* make sure the provided fd was opened */
00195        if (fd < 0 || fd > maxfd || !_cmd_pids || (pid = _cmd_pids[fd]) == 0)
00196               return -1;
00197 
00198        _cmd_pids[fd] = 0;
00199        if (close (fd) == -1)
00200               return -1;
00201 
00202        /* EINTR is ok (sort of), everything else is bad */
00203        while (waitpid (pid, &status, 0) < 0)
00204               if (errno != EINTR)
00205                      return -1;
00206 
00207        /* return child's termination status */
00208        return (WIFEXITED (status)) ? WEXITSTATUS (status) : -1;
00209 }
00210 
00211 
00212 static int
00213 _cmd_fetch_output (int fd, output * op, int flags)
00214 {
00215        size_t len = 0, i = 0, lineno = 0;
00216        size_t rsf = 6, ary_size = 0;      /* rsf = right shift factor, dec'ed uncond once */
00217        char *buf = NULL;
00218        int ret;
00219        char tmpbuf[4096];
00220 
00221        op->buf = NULL;
00222        op->buflen = 0;
00223        while ((ret = read (fd, tmpbuf, sizeof (tmpbuf))) > 0) {
00224               len = (size_t) ret;
00225               op->buf = realloc (op->buf, op->buflen + len + 1);
00226               memcpy (op->buf + op->buflen, tmpbuf, len);
00227               op->buflen += len;
00228               i++;
00229        }
00230 
00231        if (ret < 0) {
00232               printf ("read() returned %d: %s\n", ret, strerror (errno));
00233               return ret;
00234        }
00235 
00236        /* some plugins may want to keep output unbroken, and some commands
00237         * will yield no output, so return here for those */
00238        if (flags & CMD_NO_ARRAYS || !op->buf || !op->buflen)
00239               return op->buflen;
00240 
00241        /* and some may want both */
00242        if (flags & CMD_NO_ASSOC) {
00243               buf = malloc (op->buflen);
00244               memcpy (buf, op->buf, op->buflen);
00245        }
00246        else
00247               buf = op->buf;
00248 
00249        op->line = NULL;
00250        op->lens = NULL;
00251        i = 0;
00252        while (i < op->buflen) {
00253               /* make sure we have enough memory */
00254               if (lineno >= ary_size) {
00255                      /* ary_size must never be zero */
00256                      do {
00257                             ary_size = op->buflen >> --rsf;
00258                      } while (!ary_size);
00259 
00260                      op->line = realloc (op->line, ary_size * sizeof (char *));
00261                      op->lens = realloc (op->lens, ary_size * sizeof (size_t));
00262               }
00263 
00264               /* set the pointer to the string */
00265               op->line[lineno] = &buf[i];
00266 
00267               /* hop to next newline or end of buffer */
00268               while (buf[i] != '\n' && i < op->buflen)
00269                      i++;
00270               buf[i] = '\0';
00271 
00272               /* calculate the string length using pointer difference */
00273               op->lens[lineno] = (size_t) & buf[i] - (size_t) op->line[lineno];
00274 
00275               lineno++;
00276               i++;
00277        }
00278 
00279        return lineno;
00280 }
00281 
00282 
00283 int
00284 cmd_run (const char *cmdstring, output * out, output * err, int flags)
00285 {
00286        int fd, pfd_out[2], pfd_err[2];
00287        int i = 0, argc;
00288        size_t cmdlen;
00289        char **argv = NULL;
00290        char *cmd = NULL;
00291        char *str = NULL;
00292 
00293        if (cmdstring == NULL)
00294               return -1;
00295 
00296        /* initialize the structs */
00297        if (out)
00298               memset (out, 0, sizeof (output));
00299        if (err)
00300               memset (err, 0, sizeof (output));
00301 
00302        /* make copy of command string so strtok() doesn't silently modify it */
00303        /* (the calling program may want to access it later) */
00304        cmdlen = strlen (cmdstring);
00305        if ((cmd = malloc (cmdlen + 1)) == NULL)
00306               return -1;
00307        memcpy (cmd, cmdstring, cmdlen);
00308        cmd[cmdlen] = '\0';
00309 
00310        /* This is not a shell, so we don't handle "???" */
00311        if (strstr (cmdstring, "\"")) return -1;
00312 
00313        /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
00314        if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
00315               return -1;
00316 
00317        /* each arg must be whitespace-separated, so args can be a maximum
00318         * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
00319        argc = (cmdlen >> 1) + 2;
00320        argv = calloc (sizeof (char *), argc);
00321 
00322        if (argv == NULL) {
00323               printf ("%s\n", _("Could not malloc argv array in popen()"));
00324               return -1;
00325        }
00326 
00327        /* get command arguments (stupidly, but fairly quickly) */
00328        while (cmd) {
00329               str = cmd;
00330               str += strspn (str, " \t\r\n");    /* trim any leading whitespace */
00331 
00332               if (strstr (str, "'") == str) {    /* handle SIMPLE quoted strings */
00333                      str++;
00334                      if (!strstr (str, "'"))
00335                             return -1;                                              /* balanced? */
00336                      cmd = 1 + strstr (str, "'");
00337                      str[strcspn (str, "'")] = 0;
00338               }
00339               else {
00340                      if (strpbrk (str, " \t\r\n")) {
00341                             cmd = 1 + strpbrk (str, " \t\r\n");
00342                             str[strcspn (str, " \t\r\n")] = 0;
00343                      }
00344                      else {
00345                             cmd = NULL;
00346                      }
00347               }
00348 
00349               if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
00350                      cmd = NULL;
00351 
00352               argv[i++] = str;
00353        }
00354 
00355        return cmd_run_array (argv, out, err, flags);
00356 }
00357 
00358 int
00359 cmd_run_array (char *const *argv, output * out, output * err, int flags)
00360 {
00361        int fd, pfd_out[2], pfd_err[2];
00362 
00363        /* initialize the structs */
00364        if (out)
00365               memset (out, 0, sizeof (output));
00366        if (err)
00367               memset (err, 0, sizeof (output));
00368 
00369        if ((fd = _cmd_open (argv, pfd_out, pfd_err)) == -1)
00370               die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), argv[0]);
00371 
00372        if (out)
00373               out->lines = _cmd_fetch_output (pfd_out[0], out, flags);
00374        if (err)
00375               err->lines = _cmd_fetch_output (pfd_err[0], err, flags);
00376 
00377        return _cmd_close (fd);
00378 }
00379 
00380 int
00381 cmd_file_read ( char *filename, output *out, int flags)
00382 {
00383        int fd;
00384        if(out)
00385               memset (out, 0, sizeof(output));
00386 
00387        if ((fd = open(filename, O_RDONLY)) == -1) {
00388               die( STATE_UNKNOWN, _("Error opening %s: %s"), filename, strerror(errno) );
00389        }
00390        
00391        if(out)
00392               out->lines = _cmd_fetch_output (fd, out, flags);
00393 
00394        return 0;
00395 }