utils_cmd.c 10 KB

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