2 * exec.c Execute external programs.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * Copyright 2000-2004,2006 The FreeRADIUS server project
23 #include <freeradius-devel/ident.h>
26 #include <freeradius-devel/radiusd.h>
27 #include <freeradius-devel/rad_assert.h>
35 #ifdef HAVE_SYS_WAIT_H
36 # include <sys/wait.h>
39 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
42 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
45 #define MAX_ARGV (256)
48 static void tv_sub(struct timeval *end, struct timeval *start,
49 struct timeval *elapsed)
51 elapsed->tv_sec = end->tv_sec - start->tv_sec;
52 if (elapsed->tv_sec > 0) {
54 elapsed->tv_usec = USEC;
58 elapsed->tv_usec += end->tv_usec;
59 elapsed->tv_usec -= start->tv_usec;
61 if (elapsed->tv_usec >= USEC) {
62 elapsed->tv_usec -= USEC;
69 * Execute a program on successful authentication.
70 * Return 0 if exec_wait == 0.
71 * Return the exit code of the called program if exec_wait != 0.
72 * Return -1 on fork/other errors in the parent process.
74 int radius_exec_program(const char *cmd, REQUEST *request,
76 char *user_msg, int msg_len,
78 VALUE_PAIR *input_pairs,
79 VALUE_PAIR **output_pairs,
91 char * const argv[MAX_ARGV];
101 if (user_msg) *user_msg = '\0';
102 if (output_pairs) *output_pairs = NULL;
104 argc = rad_expand_xlat(request, cmd, MAX_ARGV, argv, 1,
105 sizeof(argv_buf), argv_buf);
107 RDEBUG("Exec: invalid command line '%s'.", cmd);
113 * Open a pipe for child/parent communication, if necessary.
117 RDEBUG("Exec: Couldn't open pipe: %s", strerror(errno));
122 * We're not waiting, so we don't look for a
136 * Set up the environment variables in the
137 * parent, so we don't call libc functions that
138 * hold mutexes. They might be locked when we fork,
139 * and will remain locked in the child.
143 for (vp = input_pairs; vp != NULL; vp = vp->next) {
145 * Hmm... maybe we shouldn't pass the
146 * user's password in an environment
149 snprintf(buffer, sizeof(buffer), "%s=", vp->name);
151 for (p = buffer; *p != '='; p++) {
154 } else if (isalpha((int) *p)) {
161 vp_prints_value(buffer+n, sizeof(buffer) - n, vp, shell_escape);
163 envp[envlen++] = strdup(buffer);
166 * Don't add too many attributes.
168 if (envlen == (MAX_ENVP - 1)) break;
174 pid = rad_fork(); /* remember PID */
176 pid = fork(); /* don't wait */
185 * We try to be fail-safe here. So if ANYTHING
186 * goes wrong, we exit with status 1.
190 * Open STDIN to /dev/null
192 devnull = open("/dev/null", O_RDWR);
194 RDEBUG("Exec: Failed opening /dev/null: %s\n",
198 dup2(devnull, STDIN_FILENO);
201 * Only massage the pipe handles if the parent
206 * pd[0] is the FD the child will read from,
207 * which we don't want.
209 if (close(pd[0]) != 0) {
210 RDEBUG("Exec: Can't close pipe: %s",
216 * pd[1] is the FD that the child will write to,
217 * so we make it STDOUT.
219 if (dup2(pd[1], STDOUT_FILENO) != 1) {
220 RDEBUG("Exec: Can't dup stdout: %s",
225 } else { /* no pipe, STDOUT should be /dev/null */
226 dup2(devnull, STDOUT_FILENO);
230 * If we're not debugging, then we can't do
231 * anything with the error messages, so we throw
234 * If we are debugging, then we want the error
235 * messages to go to the STDERR of the server.
237 if (debug_flag == 0) {
238 dup2(devnull, STDERR_FILENO);
243 * The server may have MANY FD's open. We don't
244 * want to leave dangling FD's for the child process
245 * to play funky games with, so we close them.
249 execve(argv[0], argv, envp);
250 RDEBUG("Exec: FAILED to execute %s: %s",
251 argv[0], strerror(errno));
256 * Free child environment variables
258 for (i = 0; envp[i] != NULL; i++) {
266 RDEBUG("Exec: Couldn't fork %s: %s", argv[0], strerror(errno));
275 * We're not waiting, exit, and ignore any child's status.
282 * Close the FD to which the child writes it's data.
284 * If we can't close it, then we close pd[0], and return an
287 if (close(pd[1]) != 0) {
288 RDEBUG("Exec: Can't close pipe: %s", strerror(errno));
295 * Try to set it non-blocking.
300 if ((flags = fcntl(pd[0], F_GETFL, NULL)) < 0) {
306 if( fcntl(pd[0], F_SETFL, flags) < 0) {
315 * Read from the pipe until we doesn't get any more or
316 * until the message is full.
319 left = sizeof(answer) - 1;
320 gettimeofday(&start, NULL);
324 struct timeval when, elapsed, wake;
329 gettimeofday(&when, NULL);
330 tv_sub(&when, &start, &elapsed);
331 if (elapsed.tv_sec >= timeout) goto too_long;
333 when.tv_sec = timeout;
335 tv_sub(&when, &elapsed, &wake);
337 rcode = select(pd[0] + 1, &fds, NULL, NULL, &wake);
340 radlog(L_INFO, "Child PID %u (%s) is taking too much time: forcing failure and killing child.", pid, argv[0]);
342 close(pd[0]); /* should give SIGPIPE to child, too */
345 * Clean up the child entry.
347 rad_waitpid(pid, &status);
351 if (errno == EINTR) continue;
357 * Read as many bytes as possible. The kernel
358 * will return the number of bytes available.
361 status = read(pd[0], answer + done, left);
365 * There's at least 1 byte ready: read it.
367 status = read(pd[0], answer + done, 1);
370 * Nothing more to read: stop.
377 * Error: See if we have to continue.
381 * We were interrupted: continue reading.
383 if (errno == EINTR) {
388 * There was another error. Most likely
389 * The child process has finished, and
397 if (left <= 0) break;
402 * Make sure that the writer can't block while writing to
403 * a pipe that no one is reading from anymore.
407 DEBUG2("Exec output: %s", answer);
410 * Parse the output, if any.
416 * For backwards compatibility, first check
417 * for plain text (user_msg).
420 n = userparse(answer, &vp);
421 if (vp) pairfree(&vp);
424 if (n == T_OP_INVALID) {
425 DEBUG("Exec plaintext: %s", answer);
427 strlcpy(user_msg, answer, msg_len);
431 * HACK: Replace '\n' with ',' so that
432 * userparse() can parse the buffer in
433 * one go (the proper way would be to
434 * fix userparse(), but oh well).
436 for (p = answer; *p; p++) {
438 *p = comma ? ' ' : ',';
442 if (*p == ',') comma++;
446 * Replace any trailing comma by a NUL.
448 if (answer[strlen(answer) - 1] == ',') {
449 answer[strlen(answer) - 1] = '\0';
452 RDEBUG("Exec output: %s", answer);
455 if (userparse(answer, &vp) == T_OP_INVALID) {
456 rad_assert(vp == NULL);
457 RDEBUG("Exec: %s: unparsable reply", cmd);
461 * Tell the caller about the value
466 } /* else the answer was a set of VP's, not a text message */
467 } /* else we didn't read anything from the child */
470 * Call rad_waitpid (should map to waitpid on non-threaded
471 * or single-server systems).
473 child_pid = rad_waitpid(pid, &status);
474 if (child_pid == 0) {
475 RDEBUG("Exec: Timeout waiting for program");
479 if (child_pid == pid) {
480 if (WIFEXITED(status)) {
481 status = WEXITSTATUS(status);
482 RDEBUG("Exec: program returned: %d", status);
487 RDEBUG("Exec: Abnormal child exit: %s", strerror(errno));
490 msg_len = msg_len; /* -Wunused */
493 RDEBUG("Exec: Wait is not supported");
498 * We're not waiting, so we don't look for a
506 * The _spawn and _exec families of functions are
507 * found in Windows compiler libraries for
508 * portability from UNIX. There is a variety of
509 * functions, including the ability to pass
510 * either a list or array of parameters, to
511 * search in the PATH or otherwise, and whether
512 * or not to pass an environment (a set of
513 * environment variables). Using _spawn, you can
514 * also specify whether you want the new process
515 * to close your program (_P_OVERLAY), to wait
516 * until the new process is finished (_P_WAIT) or
517 * for the two to run concurrently (_P_NOWAIT).
519 * _spawn and _exec are useful for instances in
520 * which you have simple requirements for running
521 * the program, don't want the overhead of the
522 * Windows header file, or are interested
523 * primarily in portability.
527 * FIXME: check return code... what is it?
529 _spawnve(_P_NOWAIT, argv[0], argv, envp);