2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 * @brief Execute external programs.
23 * @copyright 2000-2004,2006 The FreeRADIUS server project
28 #include <freeradius-devel/radiusd.h>
29 #include <freeradius-devel/rad_assert.h>
36 #ifdef HAVE_SYS_WAIT_H
37 # include <sys/wait.h>
40 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
43 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
46 #define MAX_ARGV (256)
49 static void tv_sub(struct timeval *end, struct timeval *start,
50 struct timeval *elapsed)
52 elapsed->tv_sec = end->tv_sec - start->tv_sec;
53 if (elapsed->tv_sec > 0) {
55 elapsed->tv_usec = USEC;
59 elapsed->tv_usec += end->tv_usec;
60 elapsed->tv_usec -= start->tv_usec;
62 if (elapsed->tv_usec >= USEC) {
63 elapsed->tv_usec -= USEC;
71 * @param cmd Command to execute. This is parsed into argv[] parts,
72 * then each individual argv part is xlat'ed.
73 * @param request Current reuqest
74 * @param exec_wait set to 1 if you want to read from or write to child
75 * @param[in,out] input_fd pointer to int, receives the stdin file.
76 * descriptor. Set to NULL and the child will have /dev/null on stdin
77 * @param[in,out] output_fd pinter to int, receives the stdout file
78 * descriptor. Set to NULL and child will have /dev/null on stdout.
79 * @param input_pairs list of value pairs - these will be put into
80 * the environment variables of the child.
81 * @param shell_escape values before passing them as arguments.
82 * @return PID of the child process, -1 on error.
84 pid_t radius_start_program(char const *cmd, REQUEST *request, bool exec_wait,
85 int *input_fd, int *output_fd,
86 VALUE_PAIR *input_pairs, bool shell_escape)
92 int to_child[2] = {-1, -1};
93 int from_child[2] = {-1, -1};
99 char *argv[MAX_ARGV], **argv_start = argv;
101 #define MAX_ENVP 1024
102 char *envp[MAX_ENVP];
106 * Stupid array decomposition...
108 * If we do memcpy(&argv_p, &argv, sizeof(argv_p)) src ends up being a char **
109 * pointing to the value of the first element.
111 memcpy(&argv_p, &argv_start, sizeof(argv_p));
112 argc = rad_expand_xlat(request, cmd, MAX_ARGV, argv_p, true, sizeof(argv_buf), argv_buf);
114 DEBUG("invalid command line '%s'.", cmd);
120 if (rad_debug_lvl > 2) {
121 DEBUG3("executing cmd %s", cmd);
122 for (i = 0; i < argc; i++) {
123 DEBUG3("\t[%d] %s", i, argv[i]);
130 * Open a pipe for child/parent communication, if necessary.
134 if (pipe(to_child) != 0) {
135 DEBUG("Couldn't open pipe to child: %s", fr_syserror(errno));
140 if (pipe(from_child) != 0) {
141 DEBUG("Couldn't open pipe from child: %s", fr_syserror(errno));
142 /* safe because these either need closing or are == -1 */
157 * Set up the environment variables in the
158 * parent, so we don't call libc functions that
159 * hold mutexes. They might be locked when we fork,
160 * and will remain locked in the child.
162 for (vp = fr_cursor_init(&cursor, &input_pairs);
164 vp = fr_cursor_next(&cursor)) {
166 * Hmm... maybe we shouldn't pass the
167 * user's password in an environment
170 snprintf(buffer, sizeof(buffer), "%s=", vp->da->name);
172 for (p = buffer; *p != '='; p++) {
175 } else if (isalpha((int) *p)) {
182 vp_prints_value(buffer + n, sizeof(buffer) - n, vp, shell_escape ? '"' : 0);
184 envp[envlen++] = strdup(buffer);
187 * Don't add too many attributes.
189 if (envlen == (MAX_ENVP - 1)) break;
192 * NULL terminate for execve
199 pid = rad_fork(); /* remember PID */
201 pid = fork(); /* don't wait */
210 * We try to be fail-safe here. So if ANYTHING
211 * goes wrong, we exit with status 1.
215 * Open STDIN to /dev/null
217 devnull = open("/dev/null", O_RDWR);
219 DEBUG("Failed opening /dev/null: %s\n", fr_syserror(errno));
222 * Where the status code is interpreted as a module rcode
223 * one is subtracted from it, to allow 0 to equal success
225 * 2 is RLM_MODULE_FAIL + 1
231 * Only massage the pipe handles if the parent
237 dup2(to_child[0], STDIN_FILENO);
239 dup2(devnull, STDIN_FILENO);
243 close(from_child[0]);
244 dup2(from_child[1], STDOUT_FILENO);
246 dup2(devnull, STDOUT_FILENO);
249 } else { /* no pipe, STDOUT should be /dev/null */
250 dup2(devnull, STDIN_FILENO);
251 dup2(devnull, STDOUT_FILENO);
255 * If we're not debugging, then we can't do
256 * anything with the error messages, so we throw
259 * If we are debugging, then we want the error
260 * messages to go to the STDERR of the server.
262 if (rad_debug_lvl == 0) {
263 dup2(devnull, STDERR_FILENO);
268 * The server may have MANY FD's open. We don't
269 * want to leave dangling FD's for the child process
270 * to play funky games with, so we close them.
275 * I swear the signature for execve is wrong and should
276 * take 'char const * const argv[]'.
278 * Note: execve(), unlike system(), treats all the space
279 * delimited arguments as literals, so there's no need
280 * to perform additional escaping.
282 execve(argv[0], argv, envp);
283 printf("Failed to execute \"%s\": %s", argv[0], fr_syserror(errno)); /* fork output will be captured */
286 * Where the status code is interpreted as a module rcode
287 * one is subtracted from it, to allow 0 to equal success
289 * 2 is RLM_MODULE_FAIL + 1
295 * Free child environment variables
297 for (i = 0; i < envlen; i++) {
305 DEBUG("Couldn't fork %s: %s", argv[0], fr_syserror(errno));
307 /* safe because these either need closing or are == -1 */
310 close(from_child[0]);
311 close(from_child[1]);
317 * We're not waiting, exit, and ignore any child's status.
321 * Close the ends of the pipe(s) the child is using
322 * return the ends of the pipe(s) our caller wants
326 *input_fd = to_child[1];
330 *output_fd = from_child[0];
331 close(from_child[1]);
338 DEBUG("Wait is not supported");
344 * The _spawn and _exec families of functions are
345 * found in Windows compiler libraries for
346 * portability from UNIX. There is a variety of
347 * functions, including the ability to pass
348 * either a list or array of parameters, to
349 * search in the PATH or otherwise, and whether
350 * or not to pass an environment (a set of
351 * environment variables). Using _spawn, you can
352 * also specify whether you want the new process
353 * to close your program (_P_OVERLAY), to wait
354 * until the new process is finished (_P_WAIT) or
355 * for the two to run concurrently (_P_NOWAIT).
357 * _spawn and _exec are useful for instances in
358 * which you have simple requirements for running
359 * the program, don't want the overhead of the
360 * Windows header file, or are interested
361 * primarily in portability.
365 * FIXME: check return code... what is it?
367 _spawnve(_P_NOWAIT, argv[0], argv, envp);
374 /** Read from the child process.
376 * @param fd file descriptor to read from.
377 * @param pid pid of child, will be reaped if it dies.
378 * @param timeout amount of time to wait, in seconds.
379 * @param answer buffer to write into.
380 * @param left length of buffer.
381 * @return -1 on error, or length of output.
383 int radius_readfrom_program(int fd, pid_t pid, int timeout,
384 char *answer, int left)
389 struct timeval start;
391 bool nonblock = true;
396 * Try to set it non-blocking.
401 if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
407 if( fcntl(fd, F_SETFL, flags) < 0) {
416 * Read from the pipe until we doesn't get any more or
417 * until the message is full.
419 gettimeofday(&start, NULL);
423 struct timeval when, elapsed, wake;
428 gettimeofday(&when, NULL);
429 tv_sub(&when, &start, &elapsed);
430 if (elapsed.tv_sec >= timeout) goto too_long;
432 when.tv_sec = timeout;
434 tv_sub(&when, &elapsed, &wake);
436 rcode = select(fd + 1, &fds, NULL, NULL, &wake);
439 DEBUG("Child PID %u is taking too much time: forcing failure and killing child.", (unsigned int) pid);
441 close(fd); /* should give SIGPIPE to child, too */
444 * Clean up the child entry.
446 rad_waitpid(pid, &status);
450 if (errno == EINTR) continue;
456 * Read as many bytes as possible. The kernel
457 * will return the number of bytes available.
460 status = read(fd, answer + done, left);
464 * There's at least 1 byte ready: read it.
466 status = read(fd, answer + done, 1);
469 * Nothing more to read: stop.
476 * Error: See if we have to continue.
480 * We were interrupted: continue reading.
482 if (errno == EINTR) {
487 * There was another error. Most likely
488 * The child process has finished, and
496 if (left <= 0) break;
498 #endif /* __MINGW32__ */
500 /* Strip trailing new lines */
501 while ((done > 0) && (answer[done - 1] == '\n')) {
502 answer[--done] = '\0';
508 /** Execute a program.
510 * @param[in,out] ctx to allocate new VALUE_PAIR (s) in.
511 * @param[out] out buffer to append plaintext (non valuepair) output.
512 * @param[in] outlen length of out buffer.
513 * @param[out] output_pairs list of value pairs - child stdout will be parsed and added into this list
515 * @param[in] request Current request (may be NULL).
516 * @param[in] cmd Command to execute. This is parsed into argv[] parts, then each individual argv part
518 * @param[in] input_pairs list of value pairs - these will be available in the environment of the child.
519 * @param[in] exec_wait set to 1 if you want to read from or write to child.
520 * @param[in] shell_escape values before passing them as arguments.
521 * @param[in] timeout amount of time to wait, in seconds.
523 * @return 0 if exec_wait==0, exit code if exec_wait!=0, -1 on error.
525 int radius_exec_program(TALLOC_CTX *ctx, char *out, size_t outlen, VALUE_PAIR **output_pairs,
526 REQUEST *request, char const *cmd, VALUE_PAIR *input_pairs,
527 bool exec_wait, bool shell_escape, int timeout)
541 RDEBUG2("Executing: %s:", cmd);
543 if (out) *out = '\0';
545 pid = radius_start_program(cmd, request, exec_wait, NULL, &from_child, input_pairs, shell_escape);
555 len = radius_readfrom_program(from_child, pid, timeout, answer, sizeof(answer));
558 * Failure - radius_readfrom_program will
559 * have called close(from_child) for us
561 RERROR("Failed to read from child output");
568 * Make sure that the writer can't block while writing to
569 * a pipe that no one is reading from anymore.
578 * Parse the output, if any.
582 * HACK: Replace '\n' with ',' so that
583 * fr_pair_list_afrom_str() can parse the buffer in
584 * one go (the proper way would be to
585 * fix fr_pair_list_afrom_str(), but oh well).
587 for (p = answer; *p; p++) {
589 *p = comma ? ' ' : ',';
599 * Replace any trailing comma by a NUL.
601 if (answer[len - 1] == ',') {
602 answer[--len] = '\0';
605 if (fr_pair_list_afrom_str(ctx, answer, output_pairs) == T_INVALID) {
606 RERROR("Failed parsing output from: %s: %s", cmd, fr_strerror());
607 strlcpy(out, answer, len);
611 * We've not been told to extract output pairs,
612 * just copy the programs output to the out
617 strlcpy(out, answer, outlen);
621 * Call rad_waitpid (should map to waitpid on non-threaded
622 * or single-server systems).
625 child_pid = rad_waitpid(pid, &status);
626 if (child_pid == 0) {
627 RERROR("Timeout waiting for child");
632 if (child_pid == pid) {
633 if (WIFEXITED(status)) {
634 status = WEXITSTATUS(status);
635 if ((status != 0) || (ret < 0)) {
636 RERROR("Program returned code (%d) and output '%s'", status, answer);
638 RDEBUG2("Program returned code (%d) and output '%s'", status, answer);
641 return ret < 0 ? ret : status;
645 RERROR("Abnormal child exit: %s", fr_syserror(errno));
646 #endif /* __MINGW32__ */