utils_cmd.c 10 KB

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