utils_cmd.c 9.7 KB

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