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
26 #include <freeradius-devel/ident.h>
29 #include <freeradius-devel/radiusd.h>
30 #include <freeradius-devel/rad_assert.h>
38 #ifdef HAVE_SYS_WAIT_H
39 # include <sys/wait.h>
42 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
45 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
48 #define MAX_ARGV (256)
51 static void tv_sub(struct timeval *end, struct timeval *start,
52 struct timeval *elapsed)
54 elapsed->tv_sec = end->tv_sec - start->tv_sec;
55 if (elapsed->tv_sec > 0) {
57 elapsed->tv_usec = USEC;
61 elapsed->tv_usec += end->tv_usec;
62 elapsed->tv_usec -= start->tv_usec;
64 if (elapsed->tv_usec >= USEC) {
65 elapsed->tv_usec -= USEC;
73 * @param cmd Command to execute. This is parsed into argv[] parts,
74 * then each individual argv part is xlat'ed.
75 * @param request Current reuqest
76 * @param exec_wait set to 1 if you want to read from or write to child
77 * @param[in,out] input_fd pointer to int, receives the stdin file.
78 * descriptor. Set to NULL and the child will have /dev/null on stdin
79 * @param[in,out] output_fd pinter to int, receives the stdout file
80 * descriptor. Set to NULL and child will have /dev/null on stdout.
81 * @param input_pairs list of value pairs - these will be put into
82 * the environment variables of the child.
84 * @return PID of the child process, -1 on error.
86 pid_t radius_start_program(const char *cmd, REQUEST *request,
90 VALUE_PAIR *input_pairs,
97 int to_child[2] = {-1, -1};
98 int from_child[2] = {-1, -1};
103 char *argv[MAX_ARGV];
105 #define MAX_ENVP 1024
106 char *envp[MAX_ENVP];
108 argc = rad_expand_xlat(request, cmd, MAX_ARGV, argv, 1,
109 sizeof(argv_buf), argv_buf);
111 radlog(L_ERR, "Exec-Program: invalid command line.");
117 * Open a pipe for child/parent communication, if necessary.
121 if (pipe(to_child) != 0) {
122 radlog(L_ERR, "Couldn't open pipe to child: %s",
128 if (pipe(from_child) != 0) {
129 radlog(L_ERR, "Couldn't open pipe from child: %s",
131 /* safe because these either need closing or are == -1 */
146 * Set up the environment variables in the
147 * parent, so we don't call libc functions that
148 * hold mutexes. They might be locked when we fork,
149 * and will remain locked in the child.
153 for (vp = input_pairs; vp != NULL; vp = vp->next) {
155 * Hmm... maybe we shouldn't pass the
156 * user's password in an environment
159 snprintf(buffer, sizeof(buffer), "%s=", vp->da->name);
161 for (p = buffer; *p != '='; p++) {
164 } else if (isalpha((int) *p)) {
171 vp_prints_value(buffer+n, sizeof(buffer) - n, vp, shell_escape);
173 envp[envlen++] = strdup(buffer);
176 * Don't add too many attributes.
178 if (envlen == (MAX_ENVP - 1)) break;
184 pid = rad_fork(); /* remember PID */
186 pid = fork(); /* don't wait */
195 * We try to be fail-safe here. So if ANYTHING
196 * goes wrong, we exit with status 1.
200 * Open STDIN to /dev/null
202 devnull = open("/dev/null", O_RDWR);
204 radlog(L_ERR, "Failed opening /dev/null: %s\n",
210 * Only massage the pipe handles if the parent
217 dup2(to_child[0], STDIN_FILENO);
219 dup2(devnull, STDIN_FILENO);
223 close(from_child[0]);
224 dup2(from_child[1], STDOUT_FILENO);
226 dup2(devnull, STDOUT_FILENO);
229 } else { /* no pipe, STDOUT should be /dev/null */
230 dup2(devnull, STDIN_FILENO);
231 dup2(devnull, STDOUT_FILENO);
235 * If we're not debugging, then we can't do
236 * anything with the error messages, so we throw
239 * If we are debugging, then we want the error
240 * messages to go to the STDERR of the server.
242 if (debug_flag == 0) {
243 dup2(devnull, STDERR_FILENO);
248 * The server may have MANY FD's open. We don't
249 * want to leave dangling FD's for the child process
250 * to play funky games with, so we close them.
254 execve(argv[0], argv, envp);
255 radlog(L_ERR, "Exec-Program: FAILED to execute %s: %s",
256 argv[0], strerror(errno));
261 * Free child environment variables
263 for (i = 0; envp[i] != NULL; i++) {
271 radlog(L_ERR, "Couldn't fork %s: %s",
272 argv[0], strerror(errno));
274 /* safe because these either need closing or are == -1 */
277 close(from_child[0]);
278 close(from_child[0]);
284 * We're not waiting, exit, and ignore any child's status.
288 * Close the ends of the pipe(s) the child is using
289 * return the ends of the pipe(s) our caller wants
293 *input_fd = to_child[1];
297 *output_fd = from_child[0];
298 close(from_child[1]);
305 radlog(L_ERR, "Exec-Program-Wait is not supported");
311 * The _spawn and _exec families of functions are
312 * found in Windows compiler libraries for
313 * portability from UNIX. There is a variety of
314 * functions, including the ability to pass
315 * either a list or array of parameters, to
316 * search in the PATH or otherwise, and whether
317 * or not to pass an environment (a set of
318 * environment variables). Using _spawn, you can
319 * also specify whether you want the new process
320 * to close your program (_P_OVERLAY), to wait
321 * until the new process is finished (_P_WAIT) or
322 * for the two to run concurrently (_P_NOWAIT).
324 * _spawn and _exec are useful for instances in
325 * which you have simple requirements for running
326 * the program, don't want the overhead of the
327 * Windows header file, or are interested
328 * primarily in portability.
332 * FIXME: check return code... what is it?
334 _spawnve(_P_NOWAIT, argv[0], argv, envp);
341 /** Read from the child process.
343 * @param fd file descriptor to read from.
344 * @param pid pid of child, will be reaped if it dies.
345 * @param timeout amount of time to wait, in seconds.
346 * @param answer buffer to write into.
347 * @param left length of buffer.
348 * @return -1 on error, or length of output.
350 int radius_readfrom_program(int fd, pid_t pid, int timeout, char *answer,
356 struct timeval start;
363 * Try to set it non-blocking.
368 if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
374 if( fcntl(fd, F_SETFL, flags) < 0) {
383 * Read from the pipe until we doesn't get any more or
384 * until the message is full.
386 gettimeofday(&start, NULL);
390 struct timeval when, elapsed, wake;
395 gettimeofday(&when, NULL);
396 tv_sub(&when, &start, &elapsed);
397 if (elapsed.tv_sec >= timeout) goto too_long;
399 when.tv_sec = timeout;
401 tv_sub(&when, &elapsed, &wake);
403 rcode = select(fd + 1, &fds, NULL, NULL, &wake);
406 radlog(L_ERR, "Child PID %u is taking too much time: forcing failure and killing child.", pid);
408 close(fd); /* should give SIGPIPE to child, too */
411 * Clean up the child entry.
413 rad_waitpid(pid, &status);
417 if (errno == EINTR) continue;
423 * Read as many bytes as possible. The kernel
424 * will return the number of bytes available.
427 status = read(fd, answer + done, left);
431 * There's at least 1 byte ready: read it.
433 status = read(fd, answer + done, 1);
436 * Nothing more to read: stop.
443 * Error: See if we have to continue.
447 * We were interrupted: continue reading.
449 if (errno == EINTR) {
454 * There was another error. Most likely
455 * The child process has finished, and
463 if (left <= 0) break;
465 #endif /* __MINGW32__ */
469 /** Execute a program.
471 * @param cmd Command to execute. This is parsed into argv[] parts,
472 * then each individual argv part is xlat'ed.
473 * @param request current request.
474 * @param exec_wait set to 1 if you want to read from or write to child
475 * @param user_msg buffer to append plaintext (non valuepair) output.
476 * @param msg_len length of user_msg buffer.
477 * @param input_pairs list of value pairs - these will be put into
478 * the environment variables of the child.
479 * @param[out] output_pairs list of value pairs - child stdout will be
480 * parsed and added into this list of value pairs.
481 * @param shell_escape
482 * @return 0 if exec_wait==0, exit code if exec_wait!=0, -1 on error.
484 int radius_exec_program(const char *cmd, REQUEST *request,
486 char *user_msg, int msg_len,
487 VALUE_PAIR *input_pairs,
488 VALUE_PAIR **output_pairs,
503 pid = radius_start_program(cmd, request, exec_wait, NULL, &from_child, input_pairs, shell_escape);
512 done = radius_readfrom_program(from_child, pid, 10, answer, sizeof(answer));
515 * failure - radius_readfrom_program will
516 * have called close(from_child) for us
518 DEBUG("failed to read from child output");
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, "Exec-Program: Abnormal child exit: %s",
612 #endif /* __MINGW32__ */
617 static void time_free(void *data)
622 void exec_trigger(REQUEST *request, CONF_SECTION *cs, const char *name, int quench)
632 * Use global "trigger" section if no local config is given.
635 cs = mainconfig.config;
639 * Try to use pair name, rather than reference.
641 attr = strrchr(name, '.');
650 * Find local "trigger" subsection. If it isn't found,
651 * try using the global "trigger" section, and reset the
652 * reference to the full path, rather than the sub-path.
654 subcs = cf_section_sub_find(cs, "trigger");
655 if (!subcs && (cs != mainconfig.config)) {
656 subcs = cf_section_sub_find(mainconfig.config, "trigger");
662 ci = cf_reference_item(subcs, mainconfig.config, attr);
664 DEBUG3("No such item in trigger section: %s", attr);
668 if (!cf_item_is_pair(ci)) {
669 DEBUG2("Trigger is not a configuration variable: %s", attr);
673 cp = cf_itemtopair(ci);
676 value = cf_pair_value(cp);
678 DEBUG2("Trigger has no value: %s", name);
683 * May be called for Status-Server packets.
686 if (request && request->packet) vp = request->packet->vps;
689 * Perform periodic quenching.
694 last_time = cf_data_find(cs, value);
696 last_time = rad_malloc(sizeof(*last_time));
699 if (cf_data_add(cs, value, last_time, time_free) < 0) {
706 * Send the quenched traps at most once per second.
709 time_t now = time(NULL);
710 if (*last_time == now) return;
716 DEBUG("Trigger %s -> %s", name, value);
717 radius_exec_program(value, request, 0, NULL, 0, vp, NULL, 1);