runcmd.c 9.4 KB

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