popen.c 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. /*****************************************************************************
  2. *
  3. * Nagios plugins popen
  4. *
  5. * License: GPL
  6. * Copyright (c) 2005-2007 Nagios Plugins Development Team
  7. *
  8. * Last Modified: $Date$
  9. *
  10. * Description:
  11. *
  12. * A safe alternative to popen
  13. *
  14. * Provides spopen and spclose
  15. *
  16. * FILE * spopen(const char *);
  17. * int spclose(FILE *);
  18. *
  19. * Code taken with liitle modification from "Advanced Programming for the Unix
  20. * Environment" by W. Richard Stevens
  21. *
  22. * This is considered safe in that no shell is spawned, and the environment
  23. * and path passed to the exec'd program are essentially empty. (popen create
  24. * a shell and passes the environment to it).
  25. *
  26. *
  27. * This program is free software: you can redistribute it and/or modify
  28. * it under the terms of the GNU General Public License as published by
  29. * the Free Software Foundation, either version 3 of the License, or
  30. * (at your option) any later version.
  31. *
  32. * This program is distributed in the hope that it will be useful,
  33. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  34. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  35. * GNU General Public License for more details.
  36. *
  37. * You should have received a copy of the GNU General Public License
  38. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  39. *
  40. * $Id$
  41. *
  42. *****************************************************************************/
  43. #include "common.h"
  44. /* extern so plugin has pid to kill exec'd process on timeouts */
  45. extern int timeout_interval;
  46. extern pid_t *childpid;
  47. extern int *child_stderr_array;
  48. extern FILE *child_process;
  49. FILE *spopen (const char *);
  50. int spclose (FILE *);
  51. #ifdef REDHAT_SPOPEN_ERROR
  52. RETSIGTYPE popen_sigchld_handler (int);
  53. #endif
  54. RETSIGTYPE popen_timeout_alarm_handler (int);
  55. #include <stdarg.h> /* ANSI C header file */
  56. #include <fcntl.h>
  57. #include <limits.h>
  58. #include <sys/resource.h>
  59. #ifdef HAVE_SYS_WAIT_H
  60. #include <sys/wait.h>
  61. #endif
  62. #ifndef WEXITSTATUS
  63. # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
  64. #endif
  65. #ifndef WIFEXITED
  66. # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
  67. #endif
  68. /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
  69. #if defined(SIG_IGN) && !defined(SIG_ERR)
  70. #define SIG_ERR ((Sigfunc *)-1)
  71. #endif
  72. #define min(a,b) ((a) < (b) ? (a) : (b))
  73. #define max(a,b) ((a) > (b) ? (a) : (b))
  74. int open_max (void); /* {Prog openmax} */
  75. static void err_sys (const char *, ...) __attribute__((noreturn,format(printf, 1, 2)));
  76. char *rtrim (char *, const char *);
  77. char *pname = NULL; /* caller can set this from argv[0] */
  78. /*int *childerr = NULL;*//* ptr to array allocated at run-time */
  79. /*extern pid_t *childpid = NULL; *//* ptr to array allocated at run-time */
  80. static int maxfd; /* from our open_max(), {Prog openmax} */
  81. #ifdef REDHAT_SPOPEN_ERROR
  82. static volatile int childtermd = 0;
  83. #endif
  84. FILE *
  85. spopen (const char *cmdstring)
  86. {
  87. char *env[2];
  88. char *cmd = NULL;
  89. char **argv = NULL;
  90. char *str, *tmp;
  91. int argc;
  92. int i = 0, pfd[2], pfderr[2];
  93. pid_t pid;
  94. #ifdef RLIMIT_CORE
  95. /* do not leave core files */
  96. struct rlimit limit;
  97. getrlimit (RLIMIT_CORE, &limit);
  98. limit.rlim_cur = 0;
  99. setrlimit (RLIMIT_CORE, &limit);
  100. #endif
  101. env[0] = strdup("LC_ALL=C");
  102. env[1] = '\0';
  103. /* if no command was passed, return with no error */
  104. if (cmdstring == NULL)
  105. return (NULL);
  106. /* make copy of command string so strtok() doesn't silently modify it */
  107. /* (the calling program may want to access it later) */
  108. cmd = malloc (strlen (cmdstring) + 1);
  109. if (cmd == NULL)
  110. return NULL;
  111. strcpy (cmd, cmdstring);
  112. /* This is not a shell, so we don't handle "???" */
  113. if (strstr (cmdstring, "\""))
  114. return NULL;
  115. /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
  116. if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
  117. return NULL;
  118. /* there cannot be more args than characters */
  119. argc = strlen (cmdstring) + 1; /* add 1 for NULL termination */
  120. argv = malloc (sizeof(char*)*argc);
  121. if (argv == NULL) {
  122. printf ("%s\n", _("Could not malloc argv array in popen()"));
  123. return NULL;
  124. }
  125. /* loop to get arguments to command */
  126. while (cmd) {
  127. str = cmd;
  128. str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
  129. if (i >= argc - 2) {
  130. printf ("%s\n",_("CRITICAL - You need more args!!!"));
  131. return (NULL);
  132. }
  133. if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
  134. str++;
  135. if (!strstr (str, "'"))
  136. return NULL; /* balanced? */
  137. cmd = 1 + strstr (str, "'");
  138. str[strcspn (str, "'")] = 0;
  139. }
  140. else if (strcspn(str,"'") < strcspn (str, " \t\r\n")) {
  141. /* handle --option='foo bar' strings */
  142. tmp = str + strcspn(str, "'") + 1;
  143. if (!strstr (tmp, "'"))
  144. return NULL; /* balanced? */
  145. tmp += strcspn(tmp,"'") + 1;
  146. *tmp = 0;
  147. cmd = tmp + 1;
  148. } else {
  149. if (strpbrk (str, " \t\r\n")) {
  150. cmd = 1 + strpbrk (str, " \t\r\n");
  151. str[strcspn (str, " \t\r\n")] = 0;
  152. }
  153. else {
  154. cmd = NULL;
  155. }
  156. }
  157. if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
  158. cmd = NULL;
  159. argv[i++] = str;
  160. }
  161. argv[i] = NULL;
  162. if (childpid == NULL) { /* first time through */
  163. maxfd = open_max (); /* allocate zeroed out array for child pids */
  164. if ((childpid = calloc ((size_t)maxfd, sizeof (pid_t))) == NULL)
  165. return (NULL);
  166. }
  167. if (child_stderr_array == NULL) { /* first time through */
  168. maxfd = open_max (); /* allocate zeroed out array for child pids */
  169. if ((child_stderr_array = calloc ((size_t)maxfd, sizeof (int))) == NULL)
  170. return (NULL);
  171. }
  172. if (pipe (pfd) < 0)
  173. return (NULL); /* errno set by pipe() */
  174. if (pipe (pfderr) < 0)
  175. return (NULL); /* errno set by pipe() */
  176. #ifdef REDHAT_SPOPEN_ERROR
  177. if (signal (SIGCHLD, popen_sigchld_handler) == SIG_ERR) {
  178. usage4 (_("Cannot catch SIGCHLD"));
  179. }
  180. #endif
  181. if ((pid = fork ()) < 0)
  182. return (NULL); /* errno set by fork() */
  183. else if (pid == 0) { /* child */
  184. close (pfd[0]);
  185. if (pfd[1] != STDOUT_FILENO) {
  186. dup2 (pfd[1], STDOUT_FILENO);
  187. close (pfd[1]);
  188. }
  189. close (pfderr[0]);
  190. if (pfderr[1] != STDERR_FILENO) {
  191. dup2 (pfderr[1], STDERR_FILENO);
  192. close (pfderr[1]);
  193. }
  194. /* close all descriptors in childpid[] */
  195. for (i = 0; i < maxfd; i++)
  196. if (childpid[i] > 0)
  197. close (i);
  198. execve (argv[0], argv, env);
  199. _exit (0);
  200. }
  201. close (pfd[1]); /* parent */
  202. if ((child_process = fdopen (pfd[0], "r")) == NULL)
  203. return (NULL);
  204. close (pfderr[1]);
  205. childpid[fileno (child_process)] = pid; /* remember child pid for this fd */
  206. child_stderr_array[fileno (child_process)] = pfderr[0]; /* remember STDERR */
  207. return (child_process);
  208. }
  209. int
  210. spclose (FILE * fp)
  211. {
  212. int fd, status;
  213. pid_t pid;
  214. if (childpid == NULL)
  215. return (1); /* popen() has never been called */
  216. fd = fileno (fp);
  217. if ((pid = childpid[fd]) == 0)
  218. return (1); /* fp wasn't opened by popen() */
  219. childpid[fd] = 0;
  220. if (fclose (fp) == EOF)
  221. return (1);
  222. #ifdef REDHAT_SPOPEN_ERROR
  223. while (!childtermd); /* wait until SIGCHLD */
  224. #endif
  225. while (waitpid (pid, &status, 0) < 0)
  226. if (errno != EINTR)
  227. return (1); /* error other than EINTR from waitpid() */
  228. if (WIFEXITED (status))
  229. return (WEXITSTATUS (status)); /* return child's termination status */
  230. return (1);
  231. }
  232. #ifdef OPEN_MAX
  233. static int openmax = OPEN_MAX;
  234. #else
  235. static int openmax = 0;
  236. #endif
  237. #define OPEN_MAX_GUESS 256 /* if OPEN_MAX is indeterminate */
  238. /* no guarantee this is adequate */
  239. #ifdef REDHAT_SPOPEN_ERROR
  240. RETSIGTYPE
  241. popen_sigchld_handler (int signo)
  242. {
  243. if (signo == SIGCHLD)
  244. childtermd = 1;
  245. }
  246. #endif
  247. RETSIGTYPE
  248. popen_timeout_alarm_handler (int signo)
  249. {
  250. int fh;
  251. if (signo == SIGALRM) {
  252. if (child_process != NULL) {
  253. fh=fileno (child_process);
  254. if(fh >= 0){
  255. kill (childpid[fh], SIGKILL);
  256. }
  257. printf (_("CRITICAL - Plugin timed out after %d seconds\n"),
  258. timeout_interval);
  259. } else {
  260. printf ("%s\n", _("CRITICAL - popen timeout received, but no child process"));
  261. }
  262. exit (STATE_CRITICAL);
  263. }
  264. }
  265. int
  266. open_max (void)
  267. {
  268. if (openmax == 0) { /* first time through */
  269. errno = 0;
  270. if ((openmax = sysconf (_SC_OPEN_MAX)) < 0) {
  271. if (errno == 0)
  272. openmax = OPEN_MAX_GUESS; /* it's indeterminate */
  273. else
  274. err_sys (_("sysconf error for _SC_OPEN_MAX"));
  275. }
  276. }
  277. return (openmax);
  278. }
  279. /* Fatal error related to a system call.
  280. * Print a message and die. */
  281. #define MAXLINE 2048
  282. static void
  283. err_sys (const char *fmt, ...)
  284. {
  285. int errnoflag = 1;
  286. int errno_save;
  287. char buf[MAXLINE];
  288. va_list ap;
  289. va_start (ap, fmt);
  290. /* err_doit (1, fmt, ap); */
  291. errno_save = errno; /* value caller might want printed */
  292. vsprintf (buf, fmt, ap);
  293. if (errnoflag)
  294. sprintf (buf + strlen (buf), ": %s", strerror (errno_save));
  295. strcat (buf, "\n");
  296. fflush (stdout); /* in case stdout and stderr are the same */
  297. fputs (buf, stderr);
  298. fflush (NULL); /* flushes all stdio output streams */
  299. va_end (ap);
  300. exit (1);
  301. }
  302. char *
  303. rtrim (char *str, const char *tok)
  304. {
  305. int i = 0;
  306. int j = sizeof (str);
  307. while (str != NULL && i < j) {
  308. if (*(str + i) == *tok) {
  309. sprintf (str + i, "%s", "\0");
  310. return str;
  311. }
  312. i++;
  313. }
  314. return str;
  315. }