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;
71 pid_t radius_start_program(const char *cmd, REQUEST *request,
75 VALUE_PAIR *input_pairs,
82 int to_child[2] = {-1, -1};
83 int from_child[2] = {-1, -1};
93 if (strlen(cmd) > (sizeof(mycmd) - 1)) {
94 radlog(L_ERR|L_CONS, "Command line is too long");
99 * Check for bad escapes.
101 if (cmd[strlen(cmd) - 1] == '\\') {
102 radlog(L_ERR|L_CONS, "Command line has final backslash, without a following character");
106 strlcpy(mycmd, cmd, sizeof(mycmd));
109 * Split the string into argv's BEFORE doing radius_xlat...
120 if ((*from == ' ') || (*from == '\t')) {
128 if (argc >= (MAX_ARGV - 1)) break;
131 * Copy the argv over to our buffer.
133 while (*from && (*from != ' ') && (*from != '\t')) {
134 if (to >= mycmd + sizeof(mycmd) - 1) {
135 return -1; /* ran out of space */
141 length = rad_copy_string(to, from);
143 radlog(L_ERR|L_CONS, "Invalid string passed as argument for external program");
151 if (from[1] == '{') {
154 length = rad_copy_variable(to, from);
156 radlog(L_ERR|L_CONS, "Invalid variable expansion passed as argument for external program");
161 } else { /* FIXME: catch %%{ ? */
167 if (from[1] == ' ') from++;
173 } /* end of string, or found a space */
175 *(to++) = '\0'; /* terminate the string */
179 * We have to have SOMETHING, at least.
182 radlog(L_ERR, "Exec-Program: empty command line.");
187 * Expand each string, as appropriate.
190 left = sizeof(argv_buf);
191 for (i = 0; i < argc; i++) {
195 * Don't touch argv's which won't be translated.
197 if (strchr(argv[i], '%') == NULL) continue;
199 if (!request) continue;
201 sublen = radius_xlat(to, left - 1, argv[i], request, NULL);
204 * Fail to be backwards compatible.
206 * It's yucky, but it won't break anything,
207 * and it won't cause security problems.
219 radlog(L_ERR, "Exec-Program: Ran out of space while expanding arguments.");
227 * Open a pipe for child/parent communication, if necessary.
231 if (pipe(to_child) != 0) {
232 radlog(L_ERR|L_CONS, "Couldn't open pipe to child: %s",
238 if (pipe(from_child) != 0) {
239 radlog(L_ERR|L_CONS, "Couldn't open pipe from child: %s",
241 /* safe because these either need closing or are == -1 */
256 * Set up the environment variables in the
257 * parent, so we don't call libc functions that
258 * hold mutexes. They might be locked when we fork,
259 * and will remain locked in the child.
263 for (vp = input_pairs; vp != NULL; vp = vp->next) {
265 * Hmm... maybe we shouldn't pass the
266 * user's password in an environment
269 snprintf(buffer, sizeof(buffer), "%s=", vp->name);
271 for (p = buffer; *p != '='; p++) {
274 } else if (isalpha((int) *p)) {
281 vp_prints_value(buffer+n, sizeof(buffer) - n, vp, shell_escape);
283 envp[envlen++] = strdup(buffer);
286 * Don't add too many attributes.
288 if (envlen == (MAX_ENVP - 1)) break;
294 pid = rad_fork(); /* remember PID */
296 pid = fork(); /* don't wait */
305 * We try to be fail-safe here. So if ANYTHING
306 * goes wrong, we exit with status 1.
310 * Open STDIN to /dev/null
312 devnull = open("/dev/null", O_RDWR);
314 radlog(L_ERR|L_CONS, "Failed opening /dev/null: %s\n",
320 * Only massage the pipe handles if the parent
327 dup2(to_child[0], STDIN_FILENO);
329 dup2(devnull, STDIN_FILENO);
333 close(from_child[0]);
334 dup2(from_child[1], STDOUT_FILENO);
336 dup2(devnull, STDOUT_FILENO);
339 } else { /* no pipe, STDOUT should be /dev/null */
340 dup2(devnull, STDIN_FILENO);
341 dup2(devnull, STDOUT_FILENO);
345 * If we're not debugging, then we can't do
346 * anything with the error messages, so we throw
349 * If we are debugging, then we want the error
350 * messages to go to the STDERR of the server.
352 if (debug_flag == 0) {
353 dup2(devnull, STDERR_FILENO);
358 * The server may have MANY FD's open. We don't
359 * want to leave dangling FD's for the child process
360 * to play funky games with, so we close them.
364 execve(argv[0], argv, envp);
365 radlog(L_ERR, "Exec-Program: FAILED to execute %s: %s",
366 argv[0], strerror(errno));
371 * Free child environment variables
373 for (i = 0; envp[i] != NULL; i++) {
381 radlog(L_ERR|L_CONS, "Couldn't fork %s: %s",
382 argv[0], strerror(errno));
384 /* safe because these either need closing or are == -1 */
387 close(from_child[0]);
388 close(from_child[0]);
394 * We're not waiting, exit, and ignore any child's status.
398 * Close the ends of the pipe(s) the child is using
399 * return the ends of the pipe(s) our caller wants
403 *input_fd = to_child[1];
407 *output_fd = from_child[0];
408 close(from_child[1]);
416 * read from the child process into buffer "answer" of length "left"
418 int radius_readfrom_program(int fd, pid_t pid, int timeout, char *answer, int left) {
422 struct timeval start;
429 * Try to set it non-blocking.
434 if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
440 if( fcntl(fd, F_SETFL, flags) < 0) {
449 * Read from the pipe until we doesn't get any more or
450 * until the message is full.
453 gettimeofday(&start, NULL);
457 struct timeval when, elapsed, wake;
462 gettimeofday(&when, NULL);
463 tv_sub(&when, &start, &elapsed);
464 if (elapsed.tv_sec >= timeout) goto too_long;
466 when.tv_sec = timeout;
468 tv_sub(&when, &elapsed, &wake);
470 rcode = select(fd + 1, &fds, NULL, NULL, &wake);
473 radlog(L_ERR, "Child PID %u is taking too much time: forcing failure and killing child.", pid);
475 close(fd); /* should give SIGPIPE to child, too */
478 * Clean up the child entry.
480 rad_waitpid(pid, &status);
484 if (errno == EINTR) continue;
490 * Read as many bytes as possible. The kernel
491 * will return the number of bytes available.
494 status = read(fd, answer + done, left);
498 * There's at least 1 byte ready: read it.
500 status = read(fd, answer + done, 1);
503 * Nothing more to read: stop.
510 * Error: See if we have to continue.
514 * We were interrupted: continue reading.
516 if (errno == EINTR) {
521 * There was another error. Most likely
522 * The child process has finished, and
530 if (left <= 0) break;
537 * Execute a program on successful authentication.
538 * Return 0 if exec_wait == 0.
539 * Return the exit code of the called program if exec_wait != 0.
540 * Return -1 on fork/other errors in the parent process.
542 int radius_exec_program(const char *cmd, REQUEST *request,
544 char *user_msg, int msg_len,
545 VALUE_PAIR *input_pairs,
546 VALUE_PAIR **output_pairs,
552 pid_t pid, child_pid;
558 pid = radius_start_program(cmd, request, exec_wait, NULL, &from_child, input_pairs, shell_escape);
566 done = radius_readfrom_program(from_child, pid, 10, answer, sizeof(answer));
569 * failure - radius_readfrom_program will
570 * have called close(from_child) for us
572 DEBUG("failed to read from child output");
580 * Make sure that the writer can't block while writing to
581 * a pipe that no one is reading from anymore.
585 DEBUG2("Exec-Program output: %s", answer);
588 * Parse the output, if any.
594 * For backwards compatibility, first check
595 * for plain text (user_msg).
598 n = userparse(answer, &vp);
604 if (n == T_OP_INVALID) {
605 DEBUG("Exec-Program-Wait: plaintext: %s", answer);
607 strlcpy(user_msg, answer, msg_len);
611 * HACK: Replace '\n' with ',' so that
612 * userparse() can parse the buffer in
613 * one go (the proper way would be to
614 * fix userparse(), but oh well).
616 for (p = answer; *p; p++) {
618 *p = comma ? ' ' : ',';
622 if (*p == ',') comma++;
626 * Replace any trailing comma by a NUL.
628 if (answer[strlen(answer) - 1] == ',') {
629 answer[strlen(answer) - 1] = '\0';
632 radlog(L_DBG,"Exec-Program-Wait: value-pairs: %s", answer);
633 if (userparse(answer, &vp) == T_OP_INVALID) {
634 radlog(L_ERR, "Exec-Program-Wait: %s: unparsable reply", cmd);
638 * Tell the caller about the value
643 } /* else the answer was a set of VP's, not a text message */
644 } /* else we didn't read anything from the child */
647 * Call rad_waitpid (should map to waitpid on non-threaded
648 * or single-server systems).
650 child_pid = rad_waitpid(pid, &status);
651 if (child_pid == 0) {
652 radlog(L_DBG, "Exec-Program: Timeout waiting for child");
656 if (child_pid == pid) {
657 if (WIFEXITED(status)) {
658 status = WEXITSTATUS(status);
659 radlog(L_DBG, "Exec-Program: returned: %d", status);
664 radlog(L_ERR|L_CONS, "Exec-Program: Abnormal child exit: %s",
668 msg_len = msg_len; /* -Wunused */
671 radlog(L_ERR, "Exec-Program-Wait is not supported");
676 * We're not waiting, so we don't look for a
684 * The _spawn and _exec families of functions are
685 * found in Windows compiler libraries for
686 * portability from UNIX. There is a variety of
687 * functions, including the ability to pass
688 * either a list or array of parameters, to
689 * search in the PATH or otherwise, and whether
690 * or not to pass an environment (a set of
691 * environment variables). Using _spawn, you can
692 * also specify whether you want the new process
693 * to close your program (_P_OVERLAY), to wait
694 * until the new process is finished (_P_WAIT) or
695 * for the two to run concurrently (_P_NOWAIT).
697 * _spawn and _exec are useful for instances in
698 * which you have simple requirements for running
699 * the program, don't want the overhead of the
700 * Windows header file, or are interested
701 * primarily in portability.
705 * FIXME: check return code... what is it?
707 _spawnve(_P_NOWAIT, argv[0], argv, envp);
714 void exec_trigger(REQUEST *request, CONF_SECTION *cs, const char *name)
724 * Use global "trigger" section if no local config is given.
727 cs = mainconfig.config;
731 * Try to use pair name, rather than reference.
733 attr = strrchr(name, '.');
742 * Find local "trigger" subsection. If it isn't found,
743 * try using the global "trigger" section, and reset the
744 * reference to the full path, rather than the sub-path.
746 subcs = cf_section_sub_find(cs, "trigger");
747 if (!subcs && (cs != mainconfig.config)) {
748 subcs = cf_section_sub_find(mainconfig.config, "trigger");
753 DEBUG3("No trigger subsection: ignoring trigger %s", name);
757 ci = cf_reference_item(subcs, mainconfig.config, attr);
759 DEBUG3("No such item in trigger section: %s", attr);
763 if (!cf_item_is_pair(ci)) {
764 DEBUG2("Trigger is not a configuration variable: %s", attr);
768 cp = cf_itemtopair(ci);
771 value = cf_pair_value(cp);
773 DEBUG2("Trigger has no value: %s", name);
778 * May be called for Status-Server packets.
781 if (request && request->packet) vp = request->packet->vps;
783 DEBUG("Trigger %s -> %s", name, value);
784 radius_exec_program(value, request, 0, NULL, 0, vp, NULL, 1);