4
0

utils_cmd.c 10.0 KB

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