runcmd.c 9.4 KB

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