3 * @brief Execute external programs.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 * Copyright 2000-2004,2006 The FreeRADIUS server project
24 #include <freeradius-devel/ident.h>
27 #include <freeradius-devel/radiusd.h>
28 #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.
82 * @return PID of the child process, -1 on error.
84 pid_t radius_start_program(const char *cmd, REQUEST *request,
88 VALUE_PAIR *input_pairs,
97 int to_child[2] = {-1, -1};
98 int from_child[2] = {-1, -1};
104 char *argv[MAX_ARGV];
106 #define MAX_ENVP 1024
107 char *envp[MAX_ENVP];
110 if (strlen(cmd) > (sizeof(mycmd) - 1)) {
111 radlog(L_ERR|L_CONS, "Command line is too long");
116 * Check for bad escapes.
118 if (cmd[strlen(cmd) - 1] == '\\') {
119 radlog(L_ERR|L_CONS, "Command line has final backslash, without a following character");
123 strlcpy(mycmd, cmd, sizeof(mycmd));
126 * Split the string into argv's BEFORE doing radius_xlat...
137 if ((*from == ' ') || (*from == '\t')) {
145 if (argc >= (MAX_ARGV - 1)) break;
148 * Copy the argv over to our buffer.
150 while (*from && (*from != ' ') && (*from != '\t')) {
151 if (to >= mycmd + sizeof(mycmd) - 1) {
152 return -1; /* ran out of space */
158 length = rad_copy_string(to, from);
160 radlog(L_ERR|L_CONS, "Invalid string passed as argument for external program");
168 if (from[1] == '{') {
171 length = rad_copy_variable(to, from);
173 radlog(L_ERR|L_CONS, "Invalid variable expansion passed as argument for external program");
178 } else { /* FIXME: catch %%{ ? */
184 if (from[1] == ' ') from++;
190 } /* end of string, or found a space */
192 *(to++) = '\0'; /* terminate the string */
196 * We have to have SOMETHING, at least.
199 radlog(L_ERR, "Exec-Program: empty command line.");
204 * Expand each string, as appropriate.
207 left = sizeof(argv_buf);
208 for (i = 0; i < argc; i++) {
212 * Don't touch argv's which won't be translated.
214 if (strchr(argv[i], '%') == NULL) continue;
216 if (!request) continue;
218 sublen = radius_xlat(to, left - 1, argv[i], request, NULL);
221 * Fail to be backwards compatible.
223 * It's yucky, but it won't break anything,
224 * and it won't cause security problems.
236 radlog(L_ERR, "Exec-Program: Ran out of space while expanding arguments.");
244 * Open a pipe for child/parent communication, if necessary.
248 if (pipe(to_child) != 0) {
249 radlog(L_ERR|L_CONS, "Couldn't open pipe to child: %s",
255 if (pipe(from_child) != 0) {
256 radlog(L_ERR|L_CONS, "Couldn't open pipe from child: %s",
258 /* safe because these either need closing or are == -1 */
273 * Set up the environment variables in the
274 * parent, so we don't call libc functions that
275 * hold mutexes. They might be locked when we fork,
276 * and will remain locked in the child.
280 for (vp = input_pairs; vp != NULL; vp = vp->next) {
282 * Hmm... maybe we shouldn't pass the
283 * user's password in an environment
286 snprintf(buffer, sizeof(buffer), "%s=", vp->name);
288 for (p = buffer; *p != '='; p++) {
291 } else if (isalpha((int) *p)) {
298 vp_prints_value(buffer+n, sizeof(buffer) - n, vp, shell_escape);
300 envp[envlen++] = strdup(buffer);
303 * Don't add too many attributes.
305 if (envlen == (MAX_ENVP - 1)) break;
311 pid = rad_fork(); /* remember PID */
313 pid = fork(); /* don't wait */
322 * We try to be fail-safe here. So if ANYTHING
323 * goes wrong, we exit with status 1.
327 * Open STDIN to /dev/null
329 devnull = open("/dev/null", O_RDWR);
331 radlog(L_ERR|L_CONS, "Failed opening /dev/null: %s\n",
337 * Only massage the pipe handles if the parent
344 dup2(to_child[0], STDIN_FILENO);
346 dup2(devnull, STDIN_FILENO);
350 close(from_child[0]);
351 dup2(from_child[1], STDOUT_FILENO);
353 dup2(devnull, STDOUT_FILENO);
356 } else { /* no pipe, STDOUT should be /dev/null */
357 dup2(devnull, STDIN_FILENO);
358 dup2(devnull, STDOUT_FILENO);
362 * If we're not debugging, then we can't do
363 * anything with the error messages, so we throw
366 * If we are debugging, then we want the error
367 * messages to go to the STDERR of the server.
369 if (debug_flag == 0) {
370 dup2(devnull, STDERR_FILENO);
375 * The server may have MANY FD's open. We don't
376 * want to leave dangling FD's for the child process
377 * to play funky games with, so we close them.
381 execve(argv[0], argv, envp);
382 radlog(L_ERR, "Exec-Program: FAILED to execute %s: %s",
383 argv[0], strerror(errno));
388 * Free child environment variables
390 for (i = 0; envp[i] != NULL; i++) {
398 radlog(L_ERR|L_CONS, "Couldn't fork %s: %s",
399 argv[0], strerror(errno));
401 /* safe because these either need closing or are == -1 */
404 close(from_child[0]);
405 close(from_child[0]);
411 * We're not waiting, exit, and ignore any child's status.
415 * Close the ends of the pipe(s) the child is using
416 * return the ends of the pipe(s) our caller wants
420 *input_fd = to_child[1];
424 *output_fd = from_child[0];
425 close(from_child[1]);
432 radlog(L_ERR, "Exec-Program-Wait is not supported");
438 * The _spawn and _exec families of functions are
439 * found in Windows compiler libraries for
440 * portability from UNIX. There is a variety of
441 * functions, including the ability to pass
442 * either a list or array of parameters, to
443 * search in the PATH or otherwise, and whether
444 * or not to pass an environment (a set of
445 * environment variables). Using _spawn, you can
446 * also specify whether you want the new process
447 * to close your program (_P_OVERLAY), to wait
448 * until the new process is finished (_P_WAIT) or
449 * for the two to run concurrently (_P_NOWAIT).
451 * _spawn and _exec are useful for instances in
452 * which you have simple requirements for running
453 * the program, don't want the overhead of the
454 * Windows header file, or are interested
455 * primarily in portability.
459 * FIXME: check return code... what is it?
461 _spawnve(_P_NOWAIT, argv[0], argv, envp);
468 /** Read from the child process.
470 * @param fd file descriptor to read from.
471 * @param pid pid of child, will be reaped if it dies.
472 * @param timeout amount of time to wait, in seconds.
473 * @param answer buffer to write into.
474 * @param left length of buffer.
475 * @return -1 on error, or length of output.
477 int radius_readfrom_program(int fd, pid_t pid, int timeout, char *answer,
483 struct timeval start;
490 * Try to set it non-blocking.
495 if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
501 if( fcntl(fd, F_SETFL, flags) < 0) {
510 * Read from the pipe until we doesn't get any more or
511 * until the message is full.
513 gettimeofday(&start, NULL);
517 struct timeval when, elapsed, wake;
522 gettimeofday(&when, NULL);
523 tv_sub(&when, &start, &elapsed);
524 if (elapsed.tv_sec >= timeout) goto too_long;
526 when.tv_sec = timeout;
528 tv_sub(&when, &elapsed, &wake);
530 rcode = select(fd + 1, &fds, NULL, NULL, &wake);
533 radlog(L_ERR, "Child PID %u is taking too much time: forcing failure and killing child.", pid);
535 close(fd); /* should give SIGPIPE to child, too */
538 * Clean up the child entry.
540 rad_waitpid(pid, &status);
544 if (errno == EINTR) continue;
550 * Read as many bytes as possible. The kernel
551 * will return the number of bytes available.
554 status = read(fd, answer + done, left);
558 * There's at least 1 byte ready: read it.
560 status = read(fd, answer + done, 1);
563 * Nothing more to read: stop.
570 * Error: See if we have to continue.
574 * We were interrupted: continue reading.
576 if (errno == EINTR) {
581 * There was another error. Most likely
582 * The child process has finished, and
590 if (left <= 0) break;
592 #endif /* __MINGW32__ */
596 /** Execute a program.
598 * @param cmd Command to execute. This is parsed into argv[] parts,
599 * then each individual argv part is xlat'ed.
600 * @param request current request.
601 * @param exec_wait set to 1 if you want to read from or write to child
602 * @param user_msg buffer to append plaintext (non valuepair) output.
603 * @param msg_len length of user_msg buffer.
604 * @param input_pairs list of value pairs - these will be put into
605 * the environment variables of the child.
606 * @param[out] output_pairs list of value pairs - child stdout will be
607 * parsed and added into this list of value pairs.
608 * @param shell_escape
609 * @return 0 if exec_wait==0, exit code if exec_wait!=0, -1 on error.
611 int radius_exec_program(const char *cmd, REQUEST *request,
613 char *user_msg, int msg_len,
614 VALUE_PAIR *input_pairs,
615 VALUE_PAIR **output_pairs,
630 pid = radius_start_program(cmd, request, exec_wait, NULL, &from_child, input_pairs, shell_escape);
639 done = radius_readfrom_program(from_child, pid, 10, answer, sizeof(answer));
642 * failure - radius_readfrom_program will
643 * have called close(from_child) for us
645 DEBUG("failed to read from child output");
653 * Make sure that the writer can't block while writing to
654 * a pipe that no one is reading from anymore.
658 DEBUG2("Exec-Program output: %s", answer);
661 * Parse the output, if any.
667 * For backwards compatibility, first check
668 * for plain text (user_msg).
671 n = userparse(answer, &vp);
677 if (n == T_OP_INVALID) {
678 DEBUG("Exec-Program-Wait: plaintext: %s", answer);
680 strlcpy(user_msg, answer, msg_len);
684 * HACK: Replace '\n' with ',' so that
685 * userparse() can parse the buffer in
686 * one go (the proper way would be to
687 * fix userparse(), but oh well).
689 for (p = answer; *p; p++) {
691 *p = comma ? ' ' : ',';
695 if (*p == ',') comma++;
699 * Replace any trailing comma by a NUL.
701 if (answer[strlen(answer) - 1] == ',') {
702 answer[strlen(answer) - 1] = '\0';
705 radlog(L_DBG,"Exec-Program-Wait: value-pairs: %s", answer);
706 if (userparse(answer, &vp) == T_OP_INVALID) {
707 radlog(L_ERR, "Exec-Program-Wait: %s: unparsable reply", cmd);
711 * Tell the caller about the value
716 } /* else the answer was a set of VP's, not a text message */
717 } /* else we didn't read anything from the child */
720 * Call rad_waitpid (should map to waitpid on non-threaded
721 * or single-server systems).
723 child_pid = rad_waitpid(pid, &status);
724 if (child_pid == 0) {
725 radlog(L_DBG, "Exec-Program: Timeout waiting for child");
729 if (child_pid == pid) {
730 if (WIFEXITED(status)) {
731 status = WEXITSTATUS(status);
732 radlog(L_DBG, "Exec-Program: returned: %d", status);
737 radlog(L_ERR|L_CONS, "Exec-Program: Abnormal child exit: %s",
739 #endif /* __MINGW32__ */
744 void exec_trigger(REQUEST *request, CONF_SECTION *cs, const char *name)
754 * Use global "trigger" section if no local config is given.
757 cs = mainconfig.config;
761 * Try to use pair name, rather than reference.
763 attr = strrchr(name, '.');
772 * Find local "trigger" subsection. If it isn't found,
773 * try using the global "trigger" section, and reset the
774 * reference to the full path, rather than the sub-path.
776 subcs = cf_section_sub_find(cs, "trigger");
777 if (!subcs && (cs != mainconfig.config)) {
778 subcs = cf_section_sub_find(mainconfig.config, "trigger");
783 DEBUG3("No trigger subsection: ignoring trigger %s", name);
787 ci = cf_reference_item(subcs, mainconfig.config, attr);
789 DEBUG3("No such item in trigger section: %s", attr);
793 if (!cf_item_is_pair(ci)) {
794 DEBUG2("Trigger is not a configuration variable: %s", attr);
798 cp = cf_itemtopair(ci);
801 value = cf_pair_value(cp);
803 DEBUG2("Trigger has no value: %s", name);
808 * May be called for Status-Server packets.
811 if (request && request->packet) vp = request->packet->vps;
813 DEBUG("Trigger %s -> %s", name, value);
814 radius_exec_program(value, request, 0, NULL, 0, vp, NULL, 1);