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,
77 VALUE_PAIR *input_pairs,
78 VALUE_PAIR **output_pairs,
102 if (user_msg) *user_msg = '\0';
103 if (output_pairs) *output_pairs = NULL;
105 if (strlen(cmd) > (sizeof(mycmd) - 1)) {
106 radlog(L_ERR|L_CONS, "Command line is too long");
111 * Check for bad escapes.
113 if (cmd[strlen(cmd) - 1] == '\\') {
114 radlog(L_ERR|L_CONS, "Command line has final backslash, without a following character");
118 strlcpy(mycmd, cmd, sizeof(mycmd));
121 * Split the string into argv's BEFORE doing radius_xlat...
132 if ((*from == ' ') || (*from == '\t')) {
140 if (argc >= (MAX_ARGV - 1)) break;
143 * Copy the argv over to our buffer.
145 while (*from && (*from != ' ') && (*from != '\t')) {
146 if (to >= mycmd + sizeof(mycmd) - 1) {
147 return -1; /* ran out of space */
153 length = rad_copy_string(to, from);
155 radlog(L_ERR|L_CONS, "Invalid string passed as argument for external program");
163 if (from[1] == '{') {
166 length = rad_copy_variable(to, from);
168 radlog(L_ERR|L_CONS, "Invalid variable expansion passed as argument for external program");
173 } else { /* FIXME: catch %%{ ? */
181 } /* end of string, or found a space */
183 *(to++) = '\0'; /* terminate the string */
187 * We have to have SOMETHING, at least.
190 radlog(L_ERR, "Exec-Program: empty command line.");
195 * Expand each string, as appropriate.
198 left = sizeof(argv_buf);
199 for (i = 0; i < argc; i++) {
203 * Don't touch argv's which won't be translated.
205 if (strchr(argv[i], '%') == NULL) continue;
207 if (!request) continue;
209 sublen = radius_xlat(to, left - 1, argv[i], request, NULL);
212 * Fail to be backwards compatible.
214 * It's yucky, but it won't break anything,
215 * and it won't cause security problems.
227 radlog(L_ERR, "Exec-Program: Ran out of space while expanding arguments.");
235 * Open a pipe for child/parent communication, if necessary.
239 radlog(L_ERR|L_CONS, "Couldn't open pipe: %s",
245 * We're not waiting, so we don't look for a
259 * Set up the environment variables in the
260 * parent, so we don't call libc functions that
261 * hold mutexes. They might be locked when we fork,
262 * and will remain locked in the child.
266 for (vp = input_pairs; vp != NULL; vp = vp->next) {
268 * Hmm... maybe we shouldn't pass the
269 * user's password in an environment
272 snprintf(buffer, sizeof(buffer), "%s=", vp->name);
274 for (p = buffer; *p != '='; p++) {
277 } else if (isalpha((int) *p)) {
284 vp_prints_value(buffer+n, sizeof(buffer) - n, vp, shell_escape);
286 envp[envlen++] = strdup(buffer);
289 * Don't add too many attributes.
291 if (envlen == (MAX_ENVP - 1)) break;
297 pid = rad_fork(); /* remember PID */
299 pid = fork(); /* don't wait */
308 * We try to be fail-safe here. So if ANYTHING
309 * goes wrong, we exit with status 1.
313 * Open STDIN to /dev/null
315 devnull = open("/dev/null", O_RDWR);
317 radlog(L_ERR|L_CONS, "Failed opening /dev/null: %s\n",
321 dup2(devnull, STDIN_FILENO);
324 * Only massage the pipe handles if the parent
329 * pd[0] is the FD the child will read from,
330 * which we don't want.
332 if (close(pd[0]) != 0) {
333 radlog(L_ERR|L_CONS, "Can't close pipe: %s",
339 * pd[1] is the FD that the child will write to,
340 * so we make it STDOUT.
342 if (dup2(pd[1], STDOUT_FILENO) != 1) {
343 radlog(L_ERR|L_CONS, "Can't dup stdout: %s",
348 } else { /* no pipe, STDOUT should be /dev/null */
349 dup2(devnull, STDOUT_FILENO);
353 * If we're not debugging, then we can't do
354 * anything with the error messages, so we throw
357 * If we are debugging, then we want the error
358 * messages to go to the STDERR of the server.
360 if (debug_flag == 0) {
361 dup2(devnull, STDERR_FILENO);
366 * The server may have MANY FD's open. We don't
367 * want to leave dangling FD's for the child process
368 * to play funky games with, so we close them.
372 execve(argv[0], argv, envp);
373 radlog(L_ERR, "Exec-Program: FAILED to execute %s: %s",
374 argv[0], strerror(errno));
379 * Free child environment variables
381 for (i = 0; envp[i] != NULL; i++) {
389 radlog(L_ERR|L_CONS, "Couldn't fork %s: %s",
390 argv[0], strerror(errno));
399 * We're not waiting, exit, and ignore any child's status.
406 * Close the FD to which the child writes it's data.
408 * If we can't close it, then we close pd[0], and return an
411 if (close(pd[1]) != 0) {
412 radlog(L_ERR|L_CONS, "Can't close pipe: %s", strerror(errno));
419 * Try to set it non-blocking.
424 if ((flags = fcntl(pd[0], F_GETFL, NULL)) < 0) {
430 if( fcntl(pd[0], F_SETFL, flags) < 0) {
439 * Read from the pipe until we doesn't get any more or
440 * until the message is full.
443 left = sizeof(answer) - 1;
444 gettimeofday(&start, NULL);
448 struct timeval when, elapsed, wake;
453 gettimeofday(&when, NULL);
454 tv_sub(&when, &start, &elapsed);
455 if (elapsed.tv_sec >= 10) goto too_long;
459 tv_sub(&when, &elapsed, &wake);
461 rcode = select(pd[0] + 1, &fds, NULL, NULL, &wake);
464 radlog(L_ERR, "Child PID %u is taking too much time: forcing failure and killing child.", pid);
466 close(pd[0]); /* should give SIGPIPE to child, too */
469 * Clean up the child entry.
471 rad_waitpid(pid, &status);
475 if (errno == EINTR) continue;
481 * Read as many bytes as possible. The kernel
482 * will return the number of bytes available.
485 status = read(pd[0], answer + done, left);
489 * There's at least 1 byte ready: read it.
491 status = read(pd[0], answer + done, 1);
494 * Nothing more to read: stop.
501 * Error: See if we have to continue.
505 * We were interrupted: continue reading.
507 if (errno == EINTR) {
512 * There was another error. Most likely
513 * The child process has finished, and
521 if (left <= 0) break;
526 * Make sure that the writer can't block while writing to
527 * a pipe that no one is reading from anymore.
531 DEBUG2("Exec-Program output: %s", answer);
534 * Parse the output, if any.
540 * For backwards compatibility, first check
541 * for plain text (user_msg).
544 n = userparse(answer, &vp);
550 if (n == T_OP_INVALID) {
551 DEBUG("Exec-Program-Wait: plaintext: %s", answer);
553 strlcpy(user_msg, answer, msg_len);
557 * HACK: Replace '\n' with ',' so that
558 * userparse() can parse the buffer in
559 * one go (the proper way would be to
560 * fix userparse(), but oh well).
562 for (p = answer; *p; p++) {
564 *p = comma ? ' ' : ',';
568 if (*p == ',') comma++;
572 * Replace any trailing comma by a NUL.
574 if (answer[strlen(answer) - 1] == ',') {
575 answer[strlen(answer) - 1] = '\0';
578 radlog(L_DBG,"Exec-Program-Wait: value-pairs: %s", answer);
579 if (userparse(answer, &vp) == T_OP_INVALID) {
580 radlog(L_ERR, "Exec-Program-Wait: %s: unparsable reply", cmd);
584 * Tell the caller about the value
589 } /* else the answer was a set of VP's, not a text message */
590 } /* else we didn't read anything from the child */
593 * Call rad_waitpid (should map to waitpid on non-threaded
594 * or single-server systems).
596 child_pid = rad_waitpid(pid, &status);
597 if (child_pid == 0) {
598 radlog(L_DBG, "Exec-Program: Timeout waiting for child");
602 if (child_pid == pid) {
603 if (WIFEXITED(status)) {
604 status = WEXITSTATUS(status);
605 radlog(L_DBG, "Exec-Program: returned: %d", status);
610 radlog(L_ERR|L_CONS, "Exec-Program: Abnormal child exit: %s",
614 msg_len = msg_len; /* -Wunused */
617 radlog(L_ERR, "Exec-Program-Wait is not supported");
622 * We're not waiting, so we don't look for a
630 * The _spawn and _exec families of functions are
631 * found in Windows compiler libraries for
632 * portability from UNIX. There is a variety of
633 * functions, including the ability to pass
634 * either a list or array of parameters, to
635 * search in the PATH or otherwise, and whether
636 * or not to pass an environment (a set of
637 * environment variables). Using _spawn, you can
638 * also specify whether you want the new process
639 * to close your program (_P_OVERLAY), to wait
640 * until the new process is finished (_P_WAIT) or
641 * for the two to run concurrently (_P_NOWAIT).
643 * _spawn and _exec are useful for instances in
644 * which you have simple requirements for running
645 * the program, don't want the overhead of the
646 * Windows header file, or are interested
647 * primarily in portability.
651 * FIXME: check return code... what is it?
653 _spawnve(_P_NOWAIT, argv[0], argv, envp);