popen.c 9.0 KB

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