utils_cmd.c 11 KB

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