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