runcmd.c 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /*****************************************************************************
  2. *
  3. * Nagios run command utilities
  4. *
  5. * License: GPL
  6. * Copyright (c) 2005-2014 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. unsigned int runcmd_timeout_state = STATE_CRITICAL;
  64. /* Try sysconf(_SC_OPEN_MAX) first, as it can be higher than OPEN_MAX.
  65. * If that fails and the macro isn't defined, we fall back to an educated
  66. * guess. There's no guarantee that our guess is adequate and the program
  67. * will die with SIGSEGV if it isn't and the upper boundary is breached. */
  68. #ifdef _SC_OPEN_MAX
  69. static long maxfd = 0;
  70. #elif defined(OPEN_MAX)
  71. # define maxfd OPEN_MAX
  72. #else /* sysconf macro unavailable, so guess (may be wildly inaccurate) */
  73. # define maxfd 256
  74. #endif
  75. /** prototypes **/
  76. static int np_runcmd_open(const char *, int *, int *)
  77. __attribute__((__nonnull__(1, 2, 3)));
  78. static int np_fetch_output(int, output *, int)
  79. __attribute__((__nonnull__(2)));
  80. static int np_runcmd_close(int);
  81. /* prototype imported from utils.h */
  82. extern void die (int, const char *, ...)
  83. __attribute__((__noreturn__,__format__(__printf__, 2, 3)));
  84. /* this function is NOT async-safe. It is exported so multithreaded
  85. * plugins (or other apps) can call it prior to running any commands
  86. * through this api and thus achieve async-safeness throughout the api */
  87. void np_runcmd_init(void)
  88. {
  89. #ifndef maxfd
  90. if(!maxfd && (maxfd = sysconf(_SC_OPEN_MAX)) < 0) {
  91. /* possibly log or emit a warning here, since there's no
  92. * guarantee that our guess at maxfd will be adequate */
  93. maxfd = 256;
  94. }
  95. #endif
  96. if(!np_pids) np_pids = calloc(maxfd, sizeof(pid_t));
  97. }
  98. /* Start running a command */
  99. static int
  100. np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr)
  101. {
  102. char *env[2];
  103. char *cmd = NULL;
  104. char **argv = NULL;
  105. char *str;
  106. int argc;
  107. size_t cmdlen;
  108. pid_t pid;
  109. #ifdef RLIMIT_CORE
  110. struct rlimit limit;
  111. #endif
  112. int i = 0;
  113. if(!np_pids) NP_RUNCMD_INIT;
  114. env[0] = strdup("LC_ALL=C");
  115. env[1] = '\0';
  116. /* if no command was passed, return with no error */
  117. if (cmdstring == NULL)
  118. return -1;
  119. /* make copy of command string so strtok() doesn't silently modify it */
  120. /* (the calling program may want to access it later) */
  121. cmdlen = strlen(cmdstring);
  122. if((cmd = malloc(cmdlen + 1)) == NULL) return -1;
  123. memcpy(cmd, cmdstring, cmdlen);
  124. cmd[cmdlen] = '\0';
  125. /* This is not a shell, so we don't handle "???" */
  126. if (strstr (cmdstring, "\"")) return -1;
  127. /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
  128. if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
  129. return -1;
  130. /* each arg must be whitespace-separated, so args can be a maximum
  131. * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
  132. argc = (cmdlen >> 1) + 2;
  133. argv = calloc(sizeof(char *), argc);
  134. if (argv == NULL) {
  135. printf ("%s\n", _("Could not malloc argv array in popen()"));
  136. return -1;
  137. }
  138. /* get command arguments (stupidly, but fairly quickly) */
  139. while (cmd) {
  140. str = cmd;
  141. str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
  142. if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
  143. str++;
  144. if (!strstr (str, "'")) return -1; /* balanced? */
  145. cmd = 1 + strstr (str, "'");
  146. str[strcspn (str, "'")] = 0;
  147. }
  148. else {
  149. if (strpbrk (str, " \t\r\n")) {
  150. cmd = 1 + strpbrk (str, " \t\r\n");
  151. str[strcspn (str, " \t\r\n")] = 0;
  152. }
  153. else {
  154. cmd = NULL;
  155. }
  156. }
  157. if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
  158. cmd = NULL;
  159. argv[i++] = str;
  160. }
  161. if (pipe(pfd) < 0 || pipe(pfderr) < 0 || (pid = fork()) < 0)
  162. return -1; /* errno set by the failing function */
  163. /* child runs exceve() and _exit. */
  164. if (pid == 0) {
  165. #ifdef RLIMIT_CORE
  166. /* the program we execve shouldn't leave core files */
  167. getrlimit (RLIMIT_CORE, &limit);
  168. limit.rlim_cur = 0;
  169. setrlimit (RLIMIT_CORE, &limit);
  170. #endif
  171. close (pfd[0]);
  172. if (pfd[1] != STDOUT_FILENO) {
  173. dup2 (pfd[1], STDOUT_FILENO);
  174. close (pfd[1]);
  175. }
  176. close (pfderr[0]);
  177. if (pfderr[1] != STDERR_FILENO) {
  178. dup2 (pfderr[1], STDERR_FILENO);
  179. close (pfderr[1]);
  180. }
  181. /* close all descriptors in np_pids[]
  182. * This is executed in a separate address space (pure child),
  183. * so we don't have to worry about async safety */
  184. for (i = 0; i < maxfd; i++)
  185. if(np_pids[i] > 0)
  186. close (i);
  187. execve (argv[0], argv, env);
  188. _exit (STATE_UNKNOWN);
  189. }
  190. /* parent picks up execution here */
  191. /* close childs descriptors in our address space */
  192. close(pfd[1]);
  193. close(pfderr[1]);
  194. /* tag our file's entry in the pid-list and return it */
  195. np_pids[pfd[0]] = pid;
  196. return pfd[0];
  197. }
  198. static int
  199. np_runcmd_close(int fd)
  200. {
  201. int status;
  202. pid_t pid;
  203. /* make sure this fd was opened by popen() */
  204. if(fd < 0 || fd > maxfd || !np_pids || (pid = np_pids[fd]) == 0)
  205. return -1;
  206. np_pids[fd] = 0;
  207. if (close (fd) == -1) return -1;
  208. /* EINTR is ok (sort of), everything else is bad */
  209. while (waitpid (pid, &status, 0) < 0)
  210. if (errno != EINTR) return -1;
  211. /* return child's termination status */
  212. return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1;
  213. }
  214. void
  215. runcmd_timeout_alarm_handler (int signo)
  216. {
  217. size_t i;
  218. if (signo == SIGALRM)
  219. puts(_("CRITICAL - Plugin timed out while executing system call\n"));
  220. if(np_pids) for(i = 0; i < maxfd; i++) {
  221. if(np_pids[i] != 0) kill(np_pids[i], SIGKILL);
  222. }
  223. exit (runcmd_timeout_state);
  224. }
  225. void
  226. set_runcmd_timeout_state (char *state)
  227. {
  228. if ((runcmd_timeout_state = translate_state(state)) == ERROR)
  229. usage4 (_("Timeout result must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3)."));
  230. }
  231. static int
  232. np_fetch_output(int fd, output *op, int flags)
  233. {
  234. size_t len = 0, i = 0, lineno = 0;
  235. size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
  236. char *buf = NULL;
  237. int ret;
  238. char tmpbuf[4096];
  239. op->buf = NULL;
  240. op->buflen = 0;
  241. while((ret = read(fd, tmpbuf, sizeof(tmpbuf))) > 0) {
  242. len = (size_t)ret;
  243. op->buf = realloc(op->buf, op->buflen + len + 1);
  244. memcpy(op->buf + op->buflen, tmpbuf, len);
  245. op->buflen += len;
  246. i++;
  247. }
  248. if(ret < 0) {
  249. printf("read() returned %d: %s\n", ret, strerror(errno));
  250. return ret;
  251. }
  252. /* some plugins may want to keep output unbroken, and some commands
  253. * will yield no output, so return here for those */
  254. if(flags & RUNCMD_NO_ARRAYS || !op->buf || !op->buflen)
  255. return op->buflen;
  256. /* and some may want both */
  257. if(flags & RUNCMD_NO_ASSOC) {
  258. buf = malloc(op->buflen);
  259. memcpy(buf, op->buf, op->buflen);
  260. }
  261. else buf = op->buf;
  262. op->line = NULL;
  263. op->lens = NULL;
  264. i = 0;
  265. while(i < op->buflen) {
  266. /* make sure we have enough memory */
  267. if(lineno >= ary_size) {
  268. /* ary_size must never be zero */
  269. do {
  270. ary_size = op->buflen >> --rsf;
  271. } while(!ary_size);
  272. op->line = realloc(op->line, ary_size * sizeof(char *));
  273. op->lens = realloc(op->lens, ary_size * sizeof(size_t));
  274. }
  275. /* set the pointer to the string */
  276. op->line[lineno] = &buf[i];
  277. /* hop to next newline or end of buffer */
  278. while(buf[i] != '\n' && i < op->buflen) i++;
  279. buf[i] = '\0';
  280. /* calculate the string length using pointer difference */
  281. op->lens[lineno] = (size_t)&buf[i] - (size_t)op->line[lineno];
  282. lineno++;
  283. i++;
  284. }
  285. return lineno;
  286. }
  287. int
  288. np_runcmd(const char *cmd, output *out, output *err, int flags)
  289. {
  290. int fd, pfd_out[2], pfd_err[2];
  291. /* initialize the structs */
  292. if(out) memset(out, 0, sizeof(output));
  293. if(err) memset(err, 0, sizeof(output));
  294. if((fd = np_runcmd_open(cmd, pfd_out, pfd_err)) == -1)
  295. die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd);
  296. if(out) out->lines = np_fetch_output(pfd_out[0], out, flags);
  297. if(err) err->lines = np_fetch_output(pfd_err[0], err, flags);
  298. return np_runcmd_close(fd);
  299. }