runcmd.c 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /*
  2. * $Id$
  3. *
  4. * A simple interface to executing programs from other programs, using an
  5. * optimized and safe popen()-like implementation. It is considered safe
  6. * in that no shell needs to be spawned and the environment passed to the
  7. * execve()'d program is essentially empty.
  8. *
  9. *
  10. * The code in this file is a derivative of popen.c which in turn was taken
  11. * from "Advanced Programming for the Unix Environment" by W. Richard Stevens.
  12. *
  13. * Care has been taken to make sure the functions are async-safe. The one
  14. * function which isn't is np_runcmd_init() which it doesn't make sense to
  15. * call twice anyway, so the api as a whole should be considered async-safe.
  16. *
  17. */
  18. #define NAGIOSPLUG_API_C 1
  19. /** includes **/
  20. #include "runcmd.h"
  21. #ifdef HAVE_SYS_WAIT_H
  22. # include <sys/wait.h>
  23. #endif
  24. /** macros **/
  25. #ifndef WEXITSTATUS
  26. # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
  27. #endif
  28. #ifndef WIFEXITED
  29. # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
  30. #endif
  31. /* 4.3BSD Reno <signal.h> doesn't define SIG_ERR */
  32. #if defined(SIG_IGN) && !defined(SIG_ERR)
  33. # define SIG_ERR ((Sigfunc *)-1)
  34. #endif
  35. /* This variable must be global, since there's no way the caller
  36. * can forcibly slay a dead or ungainly running program otherwise.
  37. * Multithreading apps and plugins can initialize it (via NP_RUNCMD_INIT)
  38. * in an async safe manner PRIOR to calling np_runcmd() for the first time.
  39. *
  40. * The check for initialized values is atomic and can
  41. * occur in any number of threads simultaneously. */
  42. static pid_t *np_pids = NULL;
  43. /* Try sysconf(_SC_OPEN_MAX) first, as it can be higher than OPEN_MAX.
  44. * If that fails and the macro isn't defined, we fall back to an educated
  45. * guess. There's no guarantee that our guess is adequate and the program
  46. * will die with SIGSEGV if it isn't and the upper boundary is breached. */
  47. #ifdef _SC_OPEN_MAX
  48. static long maxfd = 0;
  49. #elif defined(OPEN_MAX)
  50. # define maxfd OPEN_MAX
  51. #else /* sysconf macro unavailable, so guess (may be wildly inaccurate) */
  52. # define maxfd 256
  53. #endif
  54. /** prototypes **/
  55. static int np_runcmd_open(const char *, int *, int *)
  56. __attribute__((__nonnull__(1, 2, 3)));
  57. static int np_fetch_output(int, output *, int)
  58. __attribute__((__nonnull__(2)));
  59. static int np_runcmd_close(int);
  60. /* prototype imported from utils.h */
  61. extern void die (int, const char *, ...)
  62. __attribute__((__noreturn__,__format__(__printf__, 2, 3)));
  63. /* this function is NOT async-safe. It is exported so multithreaded
  64. * plugins (or other apps) can call it prior to running any commands
  65. * through this api and thus achieve async-safeness throughout the api */
  66. void np_runcmd_init(void)
  67. {
  68. #ifndef maxfd
  69. if(!maxfd && (maxfd = sysconf(_SC_OPEN_MAX)) < 0) {
  70. /* possibly log or emit a warning here, since there's no
  71. * guarantee that our guess at maxfd will be adequate */
  72. maxfd = 256;
  73. }
  74. #endif
  75. if(!np_pids) np_pids = calloc(maxfd, sizeof(pid_t));
  76. }
  77. /* Start running a command */
  78. static int
  79. np_runcmd_open(const char *cmdstring, int *pfd, int *pfderr)
  80. {
  81. char *env[2];
  82. char *cmd = NULL;
  83. char **argv = NULL;
  84. char *str;
  85. int argc;
  86. size_t cmdlen;
  87. pid_t pid;
  88. #ifdef RLIMIT_CORE
  89. struct rlimit limit;
  90. #endif
  91. int i = 0;
  92. if(!np_pids) NP_RUNCMD_INIT;
  93. env[0] = strdup("LC_ALL=C");
  94. env[1] = '\0';
  95. /* if no command was passed, return with no error */
  96. if (cmdstring == NULL)
  97. return -1;
  98. /* make copy of command string so strtok() doesn't silently modify it */
  99. /* (the calling program may want to access it later) */
  100. cmdlen = strlen(cmdstring);
  101. if((cmd = malloc(cmdlen + 1)) == NULL) return -1;
  102. memcpy(cmd, cmdstring, cmdlen);
  103. cmd[cmdlen] = '\0';
  104. /* This is not a shell, so we don't handle "???" */
  105. if (strstr (cmdstring, "\"")) return -1;
  106. /* allow single quotes, but only if non-whitesapce doesn't occur on both sides */
  107. if (strstr (cmdstring, " ' ") || strstr (cmdstring, "'''"))
  108. return -1;
  109. /* each arg must be whitespace-separated, so args can be a maximum
  110. * of (len / 2) + 1. We add 1 extra to the mix for NULL termination */
  111. argc = (cmdlen >> 1) + 2;
  112. argv = calloc(sizeof(char *), argc);
  113. if (argv == NULL) {
  114. printf (_("Could not malloc argv array in popen()\n"));
  115. return -1;
  116. }
  117. /* get command arguments (stupidly, but fairly quickly) */
  118. while (cmd) {
  119. str = cmd;
  120. str += strspn (str, " \t\r\n"); /* trim any leading whitespace */
  121. if (strstr (str, "'") == str) { /* handle SIMPLE quoted strings */
  122. str++;
  123. if (!strstr (str, "'")) return -1; /* balanced? */
  124. cmd = 1 + strstr (str, "'");
  125. str[strcspn (str, "'")] = 0;
  126. }
  127. else {
  128. if (strpbrk (str, " \t\r\n")) {
  129. cmd = 1 + strpbrk (str, " \t\r\n");
  130. str[strcspn (str, " \t\r\n")] = 0;
  131. }
  132. else {
  133. cmd = NULL;
  134. }
  135. }
  136. if (cmd && strlen (cmd) == strspn (cmd, " \t\r\n"))
  137. cmd = NULL;
  138. argv[i++] = str;
  139. }
  140. if (pipe(pfd) < 0 || pipe(pfderr) < 0 || (pid = fork()) < 0)
  141. return -1; /* errno set by the failing function */
  142. /* child runs exceve() and _exit. */
  143. if (pid == 0) {
  144. #ifdef RLIMIT_CORE
  145. /* the program we execve shouldn't leave core files */
  146. getrlimit (RLIMIT_CORE, &limit);
  147. limit.rlim_cur = 0;
  148. setrlimit (RLIMIT_CORE, &limit);
  149. #endif
  150. close (pfd[0]);
  151. if (pfd[1] != STDOUT_FILENO) {
  152. dup2 (pfd[1], STDOUT_FILENO);
  153. close (pfd[1]);
  154. }
  155. close (pfderr[0]);
  156. if (pfderr[1] != STDERR_FILENO) {
  157. dup2 (pfderr[1], STDERR_FILENO);
  158. close (pfderr[1]);
  159. }
  160. /* close all descriptors in np_pids[]
  161. * This is executed in a separate address space (pure child),
  162. * so we don't have to worry about async safety */
  163. for (i = 0; i < maxfd; i++)
  164. if(np_pids[i] > 0)
  165. close (i);
  166. execve (argv[0], argv, env);
  167. _exit (STATE_UNKNOWN);
  168. }
  169. /* parent picks up execution here */
  170. /* close childs descriptors in our address space */
  171. close(pfd[1]);
  172. close(pfderr[1]);
  173. /* tag our file's entry in the pid-list and return it */
  174. np_pids[pfd[0]] = pid;
  175. return pfd[0];
  176. }
  177. static int
  178. np_runcmd_close(int fd)
  179. {
  180. int status;
  181. pid_t pid;
  182. /* make sure this fd was opened by popen() */
  183. if(fd < 0 || fd > maxfd || !np_pids || (pid = np_pids[fd]) == 0)
  184. return -1;
  185. np_pids[fd] = 0;
  186. if (close (fd) == -1) return -1;
  187. /* EINTR is ok (sort of), everything else is bad */
  188. while (waitpid (pid, &status, 0) < 0)
  189. if (errno != EINTR) return -1;
  190. /* return child's termination status */
  191. return (WIFEXITED(status)) ? WEXITSTATUS(status) : -1;
  192. }
  193. void
  194. popen_timeout_alarm_handler (int signo)
  195. {
  196. size_t i;
  197. if (signo == SIGALRM)
  198. puts(_("CRITICAL - Plugin timed out while executing system call\n"));
  199. if(np_pids) for(i = 0; i < maxfd; i++) {
  200. if(np_pids[i] != 0) kill(np_pids[i], SIGKILL);
  201. }
  202. exit (STATE_CRITICAL);
  203. }
  204. static int
  205. np_fetch_output(int fd, output *op, int flags)
  206. {
  207. size_t len = 0, i = 0, lineno = 0;
  208. size_t rsf = 6, ary_size = 0; /* rsf = right shift factor, dec'ed uncond once */
  209. char *buf = NULL;
  210. int ret;
  211. char tmpbuf[4096];
  212. op->buf = NULL;
  213. op->buflen = 0;
  214. while((ret = read(fd, tmpbuf, sizeof(tmpbuf))) > 0) {
  215. len = (size_t)ret;
  216. op->buf = realloc(op->buf, op->buflen + len + 1);
  217. memcpy(op->buf + op->buflen, tmpbuf, len);
  218. op->buflen += len;
  219. i++;
  220. }
  221. if(ret < 0) {
  222. printf("read() returned %d: %s\n", ret, strerror(errno));
  223. return ret;
  224. }
  225. /* some plugins may want to keep output unbroken, and some commands
  226. * will yield no output, so return here for those */
  227. if(flags & RUNCMD_NO_ARRAYS || !op->buf || !op->buflen)
  228. return op->buflen;
  229. /* and some may want both */
  230. if(flags & RUNCMD_NO_ASSOC) {
  231. buf = malloc(op->buflen);
  232. memcpy(buf, op->buf, op->buflen);
  233. }
  234. else buf = op->buf;
  235. op->line = NULL;
  236. op->lens = NULL;
  237. i = 0;
  238. while(i < op->buflen) {
  239. /* make sure we have enough memory */
  240. if(lineno >= ary_size) {
  241. /* ary_size must never be zero */
  242. do {
  243. ary_size = op->buflen >> --rsf;
  244. } while(!ary_size);
  245. op->line = realloc(op->line, ary_size * sizeof(char *));
  246. op->lens = realloc(op->lens, ary_size * sizeof(size_t));
  247. }
  248. /* set the pointer to the string */
  249. op->line[lineno] = &buf[i];
  250. /* hop to next newline or end of buffer */
  251. while(buf[i] != '\n' && i < op->buflen) i++;
  252. buf[i] = '\0';
  253. /* calculate the string length using pointer difference */
  254. op->lens[lineno] = (size_t)&buf[i] - (size_t)op->line[lineno];
  255. lineno++;
  256. i++;
  257. }
  258. return lineno;
  259. }
  260. int
  261. np_runcmd(const char *cmd, output *out, output *err, int flags)
  262. {
  263. int fd, pfd_out[2], pfd_err[2];
  264. /* initialize the structs */
  265. if(out) memset(out, 0, sizeof(output));
  266. if(err) memset(err, 0, sizeof(output));
  267. if((fd = np_runcmd_open(cmd, pfd_out, pfd_err)) == -1)
  268. die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd);
  269. if(out) out->lines = np_fetch_output(pfd_out[0], out, flags);
  270. if(err) err->lines = np_fetch_output(pfd_err[0], err, flags);
  271. return np_runcmd_close(fd);
  272. }