runcmd.c 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /*****************************************************************************
  2. *
  3. * Nagios run command utilities
  4. *
  5. * License: GPL
  6. * Copyright (c) 2005-2006 Nagios Plugins Development Team
  7. *
  8. * Last Modified: $Date$
  9. *
  10. * Description :
  11. *
  12. * A simple interface to executing programs from other programs, using an
  13. * optimized and safe popen()-like implementation. It is considered safe
  14. * in that no shell needs to be spawned and the environment passed to the
  15. * execve()'d program is essentially empty.
  16. *
  17. * The code in this file is a derivative of popen.c which in turn was taken
  18. * from "Advanced Programming for the Unix Environment" by W. Richard Stevens.
  19. *
  20. * Care has been taken to make sure the functions are async-safe. The one
  21. * function which isn't is np_runcmd_init() which it doesn't make sense to
  22. * call twice anyway, so the api as a whole should be considered async-safe.
  23. *
  24. *
  25. * This program is free software: you can redistribute it and/or modify
  26. * it under the terms of the GNU General Public License as published by
  27. * the Free Software Foundation, either version 3 of the License, or
  28. * (at your option) any later version.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU General Public License
  36. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  37. *
  38. * $Id$
  39. *
  40. *****************************************************************************/
  41. #define NAGIOSPLUG_API_C 1
  42. /** includes **/
  43. #include "runcmd.h"
  44. #ifdef HAVE_SYS_WAIT_H
  45. # include <sys/wait.h>
  46. #endif
  47. /** macros **/
  48. #ifndef WEXITSTATUS
  49. # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
  50. #endif
  51. #ifndef WIFEXITED
  52. # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
  53. #endif
  54. /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
  55. #if defined(SIG_IGN) && !defined(SIG_ERR)
  56. # define SIG_ERR ((Sigfunc *)-1)
  57. #endif
  58. /* This variable must be global, since there's no way the caller
  59. * can forcibly slay a dead or ungainly running program otherwise.
  60. * Multithreading apps and plugins can initialize it (via NP_RUNCMD_INIT)
  61. * in an async safe manner PRIOR to calling np_runcmd() for the first time.
  62. *
  63. * The check for initialized values is atomic and can
  64. * occur in any number of threads simultaneously. */
  65. static pid_t *np_pids = NULL;
  66. /* Try sysconf(_SC_OPEN_MAX) first, as it can be higher than OPEN_MAX.
  67. * If that fails and the macro isn't defined, we fall back to an educated
  68. * guess. There's no guarantee that our guess is adequate and the program
  69. * will die with SIGSEGV if it isn't and the upper boundary is breached. */
  70. #ifdef _SC_OPEN_MAX
  71. static long maxfd = 0;
  72. #elif defined(OPEN_MAX)
  73. # define maxfd OPEN_MAX
  74. #else /* sysconf macro unavailable, so guess (may be wildly inaccurate) */
  75. # define maxfd 256
  76. #endif
  77. /** prototypes **/
  78. static int np_runcmd_open(const char *, int *, int *)
  79. __attribute__((__nonnull__(1, 2, 3)));
  80. static int np_fetch_output(int, output *, int)
  81. __attribute__((__nonnull__(2)));
  82. static int np_runcmd_close(int);
  83. /* prototype imported from utils.h */
  84. extern void die (int, const char *, ...)
  85. __attribute__((__noreturn__,__format__(__printf__, 2, 3)));
  86. /* this function is NOT async-safe. It is exported so multithreaded
  87. * plugins (or other apps) can call it prior to running any commands
  88. * through this api and thus achieve async-safeness throughout the api */
  89. void np_runcmd_init(void)
  90. {
  91. #ifndef maxfd
  92. if(!maxfd && (maxfd = sysconf(_SC_OPEN_MAX)) < 0) {
  93. /* possibly log or emit a warning here, since there's no
  94. * guarantee that our guess at maxfd will be adequate */
  95. maxfd = 256;
  96. }
  97. #endif
  98. if(!np_pids) np_pids = calloc(maxfd, sizeof(pid_t));
  99. }
  100. /* Start running a command */
  101. static int
  102. np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr)
  103. {
  104. char *env[2];
  105. char *cmd = NULL;
  106. char **argv = NULL;
  107. char *str;
  108. int argc;
  109. size_t cmdlen;
  110. pid_t pid;
  111. #ifdef RLIMIT_CORE
  112. struct rlimit limit;
  113. #endif
  114. int i = 0;
  115. if(!np_pids) NP_RUNCMD_INIT;
  116. env[0] = strdup("LC_ALL=C");
  117. env[1] = '\0';
  118. /* if no command was passed, return with no error */
  119. if (cmdstring == NULL)
  120. return -1;
  121. /* make copy of command string so strtok() doesn't silently modify it */
  122. /* (the calling program may want to access it later) */
  123. cmdlen = strlen(cmdstring);
  124. if((cmd = malloc(cmdlen + 1)) == NULL) return -1;
  125. memcpy(cmd, cmdstring, cmdlen);
  126. cmd[cmdlen] = '\0';
  127. /* This is not a shell, so we don't handle "???" */
  128. if (strstr (cmdstring, "\"")) return -1;
  129. /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
  130. if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
  131. return -1;
  132. /* each arg must be whitespace-separated, so args can be a maximum
  133. * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
  134. argc = (cmdlen >> 1) + 2;
  135. argv = calloc(sizeof(char *), argc);
  136. if (argv == NULL) {
  137. printf ("%s\n", _("Could not malloc argv array in popen()"));
  138. return -1;
  139. }
  140. /* get command arguments (stupidly, but fairly quickly) */
  141. while (cmd) {
  142. str = cmd;
  143. str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
  144. if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
  145. str++;
  146. if (!strstr (str, "'")) return -1; /* balanced? */
  147. cmd = 1 + strstr (str, "'");
  148. str[strcspn (str, "'")] = 0;
  149. }
  150. else {
  151. if (strpbrk (str, " \t\r\n")) {
  152. cmd = 1 + strpbrk (str, " \t\r\n");
  153. str[strcspn (str, " \t\r\n")] = 0;
  154. }
  155. else {
  156. cmd = NULL;
  157. }
  158. }
  159. if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
  160. cmd = NULL;
  161. argv[i++] = str;
  162. }
  163. if (pipe(pfd) < 0 || pipe(pfderr) < 0 || (pid = fork()) < 0)
  164. return -1; /* errno set by the failing function */
  165. /* child runs exceve() and _exit. */
  166. if (pid == 0) {
  167. #ifdef RLIMIT_CORE
  168. /* the program we execve shouldn't leave core files */
  169. getrlimit (RLIMIT_CORE, &limit);
  170. limit.rlim_cur = 0;
  171. setrlimit (RLIMIT_CORE, &limit);
  172. #endif
  173. close (pfd[0]);
  174. if (pfd[1] != STDOUT_FILENO) {
  175. dup2 (pfd[1], STDOUT_FILENO);
  176. close (pfd[1]);
  177. }
  178. close (pfderr[0]);
  179. if (pfderr[1] != STDERR_FILENO) {
  180. dup2 (pfderr[1], STDERR_FILENO);
  181. close (pfderr[1]);
  182. }
  183. /* close all descriptors in np_pids[]
  184. * This is executed in a separate address space (pure child),
  185. * so we don't have to worry about async safety */
  186. for (i = 0; i < maxfd; i++)
  187. if(np_pids[i] > 0)
  188. close (i);
  189. execve (argv[0], argv, env);
  190. _exit (STATE_UNKNOWN);
  191. }
  192. /* parent picks up execution here */
  193. /* close childs descriptors in our address space */
  194. close(pfd[1]);
  195. close(pfderr[1]);
  196. /* tag our file's entry in the pid-list and return it */
  197. np_pids[pfd[0]] = pid;
  198. return pfd[0];
  199. }
  200. static int
  201. np_runcmd_close(int fd)
  202. {
  203. int status;
  204. pid_t pid;
  205. /* make sure this fd was opened by popen() */
  206. if(fd < 0 || fd > maxfd || !np_pids || (pid = np_pids[fd]) == 0)
  207. return -1;
  208. np_pids[fd] = 0;
  209. if (close (fd) == -1) return -1;
  210. /* EINTR is ok (sort of), everything else is bad */
  211. while (waitpid (pid, &status, 0) < 0)
  212. if (errno != EINTR) return -1;
  213. /* return child's termination status */
  214. return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1;
  215. }
  216. void
  217. popen_timeout_alarm_handler (int signo)
  218. {
  219. size_t i;
  220. if (signo == SIGALRM)
  221. puts(_("CRITICAL - Plugin timed out while executing system call\n"));
  222. if(np_pids) for(i = 0; i < maxfd; i++) {
  223. if(np_pids[i] != 0) kill(np_pids[i], SIGKILL);
  224. }
  225. exit (STATE_CRITICAL);
  226. }
  227. static int
  228. np_fetch_output(int fd, output *op, int flags)
  229. {
  230. size_t len = 0, i = 0, lineno = 0;
  231. size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
  232. char *buf = NULL;
  233. int ret;
  234. char tmpbuf[4096];
  235. op->buf = NULL;
  236. op->buflen = 0;
  237. while((ret = read(fd, tmpbuf, sizeof(tmpbuf))) > 0) {
  238. len = (size_t)ret;
  239. op->buf = realloc(op->buf, op->buflen + len + 1);
  240. memcpy(op->buf + op->buflen, tmpbuf, len);
  241. op->buflen += len;
  242. i++;
  243. }
  244. if(ret < 0) {
  245. printf("read() returned %d: %s\n", ret, strerror(errno));
  246. return ret;
  247. }
  248. /* some plugins may want to keep output unbroken, and some commands
  249. * will yield no output, so return here for those */
  250. if(flags & RUNCMD_NO_ARRAYS || !op->buf || !op->buflen)
  251. return op->buflen;
  252. /* and some may want both */
  253. if(flags & RUNCMD_NO_ASSOC) {
  254. buf = malloc(op->buflen);
  255. memcpy(buf, op->buf, op->buflen);
  256. }
  257. else buf = op->buf;
  258. op->line = NULL;
  259. op->lens = NULL;
  260. i = 0;
  261. while(i < op->buflen) {
  262. /* make sure we have enough memory */
  263. if(lineno >= ary_size) {
  264. /* ary_size must never be zero */
  265. do {
  266. ary_size = op->buflen >> --rsf;
  267. } while(!ary_size);
  268. op->line = realloc(op->line, ary_size * sizeof(char *));
  269. op->lens = realloc(op->lens, ary_size * sizeof(size_t));
  270. }
  271. /* set the pointer to the string */
  272. op->line[lineno] = &buf[i];
  273. /* hop to next newline or end of buffer */
  274. while(buf[i] != '\n' && i < op->buflen) i++;
  275. buf[i] = '\0';
  276. /* calculate the string length using pointer difference */
  277. op->lens[lineno] = (size_t)&buf[i] - (size_t)op->line[lineno];
  278. lineno++;
  279. i++;
  280. }
  281. return lineno;
  282. }
  283. int
  284. np_runcmd(const char *cmd, output *out, output *err, int flags)
  285. {
  286. int fd, pfd_out[2], pfd_err[2];
  287. /* initialize the structs */
  288. if(out) memset(out, 0, sizeof(output));
  289. if(err) memset(err, 0, sizeof(output));
  290. if((fd = np_runcmd_open(cmd, pfd_out, pfd_err)) == -1)
  291. die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd);
  292. if(out) out->lines = np_fetch_output(pfd_out[0], out, flags);
  293. if(err) err->lines = np_fetch_output(pfd_err[0], err, flags);
  294. return np_runcmd_close(fd);
  295. }