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
28 #include <freeradius-devel/radiusd.h>
29 #include <freeradius-devel/rad_assert.h>
37 #ifdef HAVE_SYS_WAIT_H
38 # include <sys/wait.h>
41 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
44 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
47 #define MAX_ARGV (256)
50 static void tv_sub(struct timeval *end, struct timeval *start,
51 struct timeval *elapsed)
53 elapsed->tv_sec = end->tv_sec - start->tv_sec;
54 if (elapsed->tv_sec > 0) {
56 elapsed->tv_usec = USEC;
60 elapsed->tv_usec += end->tv_usec;
61 elapsed->tv_usec -= start->tv_usec;
63 if (elapsed->tv_usec >= USEC) {
64 elapsed->tv_usec -= USEC;
72 * @param cmd Command to execute. This is parsed into argv[] parts,
73 * then each individual argv part is xlat'ed.
74 * @param request Current reuqest
75 * @param exec_wait set to 1 if you want to read from or write to child
76 * @param[in,out] input_fd pointer to int, receives the stdin file.
77 * descriptor. Set to NULL and the child will have /dev/null on stdin
78 * @param[in,out] output_fd pinter to int, receives the stdout file
79 * descriptor. Set to NULL and child will have /dev/null on stdout.
80 * @param input_pairs list of value pairs - these will be put into
81 * the environment variables of the child.
83 * @return PID of the child process, -1 on error.
85 pid_t radius_start_program(char const *cmd, REQUEST *request,
89 VALUE_PAIR *input_pairs,
96 int to_child[2] = {-1, -1};
97 int from_child[2] = {-1, -1};
102 char const *argv[MAX_ARGV];
105 #define MAX_ENVP 1024
106 char *envp[MAX_ENVP];
108 memcpy(&argv_p, &argv, sizeof(argv_p));
110 argc = rad_expand_xlat(request, cmd, MAX_ARGV, argv, 1, sizeof(argv_buf), argv_buf);
112 RDEBUG("invalid command line '%s'.", cmd);
118 if (debug_flag > 2) {
119 RDEBUG3("executing cmd %s", cmd);
120 for (i = 0; i < argc; i++) {
121 RDEBUG3("\t[%d] %s", i, argv[i]);
128 * Open a pipe for child/parent communication, if necessary.
132 if (pipe(to_child) != 0) {
133 RDEBUG("Couldn't open pipe to child: %s", strerror(errno));
138 if (pipe(from_child) != 0) {
139 RDEBUG("Couldn't open pipe from child: %s", strerror(errno));
140 /* safe because these either need closing or are == -1 */
155 * Set up the environment variables in the
156 * parent, so we don't call libc functions that
157 * hold mutexes. They might be locked when we fork,
158 * and will remain locked in the child.
162 for (vp = input_pairs; vp != NULL; vp = vp->next) {
164 * Hmm... maybe we shouldn't pass the
165 * user's password in an environment
168 snprintf(buffer, sizeof(buffer), "%s=", vp->da->name);
170 for (p = buffer; *p != '='; p++) {
173 } else if (isalpha((int) *p)) {
180 vp_prints_value(buffer+n, sizeof(buffer) - n, vp, shell_escape);
182 envp[envlen++] = strdup(buffer);
185 * Don't add too many attributes.
187 if (envlen == (MAX_ENVP - 1)) break;
193 pid = rad_fork(); /* remember PID */
195 pid = fork(); /* don't wait */
204 * We try to be fail-safe here. So if ANYTHING
205 * goes wrong, we exit with status 1.
209 * Open STDIN to /dev/null
211 devnull = open("/dev/null", O_RDWR);
213 RDEBUG("Failed opening /dev/null: %s\n", strerror(errno));
219 * Only massage the pipe handles if the parent
226 dup2(to_child[0], STDIN_FILENO);
228 dup2(devnull, STDIN_FILENO);
232 close(from_child[0]);
233 dup2(from_child[1], STDOUT_FILENO);
235 dup2(devnull, STDOUT_FILENO);
238 } else { /* no pipe, STDOUT should be /dev/null */
239 dup2(devnull, STDIN_FILENO);
240 dup2(devnull, STDOUT_FILENO);
244 * If we're not debugging, then we can't do
245 * anything with the error messages, so we throw
248 * If we are debugging, then we want the error
249 * messages to go to the STDERR of the server.
251 if (debug_flag == 0) {
252 dup2(devnull, STDERR_FILENO);
257 * The server may have MANY FD's open. We don't
258 * want to leave dangling FD's for the child process
259 * to play funky games with, so we close them.
263 execve(argv_p[0], argv_p, envp);
264 RDEBUGW("Failed to execute %s: %s", argv[0], strerror(errno));
269 * Free child environment variables
271 for (i = 0; envp[i] != NULL; i++) {
279 RDEBUG("Couldn't fork %s: %s", argv[0], strerror(errno));
281 /* safe because these either need closing or are == -1 */
284 close(from_child[0]);
285 close(from_child[0]);
291 * We're not waiting, exit, and ignore any child's status.
295 * Close the ends of the pipe(s) the child is using
296 * return the ends of the pipe(s) our caller wants
300 *input_fd = to_child[1];
304 *output_fd = from_child[0];
305 close(from_child[1]);
312 RDEBUG("Wait is not supported");
318 * The _spawn and _exec families of functions are
319 * found in Windows compiler libraries for
320 * portability from UNIX. There is a variety of
321 * functions, including the ability to pass
322 * either a list or array of parameters, to
323 * search in the PATH or otherwise, and whether
324 * or not to pass an environment (a set of
325 * environment variables). Using _spawn, you can
326 * also specify whether you want the new process
327 * to close your program (_P_OVERLAY), to wait
328 * until the new process is finished (_P_WAIT) or
329 * for the two to run concurrently (_P_NOWAIT).
331 * _spawn and _exec are useful for instances in
332 * which you have simple requirements for running
333 * the program, don't want the overhead of the
334 * Windows header file, or are interested
335 * primarily in portability.
339 * FIXME: check return code... what is it?
341 _spawnve(_P_NOWAIT, argv[0], argv, envp);
348 /** Read from the child process.
350 * @param request The current request.
351 * @param fd file descriptor to read from.
352 * @param pid pid of child, will be reaped if it dies.
353 * @param timeout amount of time to wait, in seconds.
354 * @param answer buffer to write into.
355 * @param left length of buffer.
356 * @return -1 on error, or length of output.
358 int radius_readfrom_program(REQUEST *request, int fd, pid_t pid, int timeout,
359 char *answer, int left)
364 struct timeval start;
371 * Try to set it non-blocking.
376 if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
382 if( fcntl(fd, F_SETFL, flags) < 0) {
391 * Read from the pipe until we doesn't get any more or
392 * until the message is full.
394 gettimeofday(&start, NULL);
398 struct timeval when, elapsed, wake;
403 gettimeofday(&when, NULL);
404 tv_sub(&when, &start, &elapsed);
405 if (elapsed.tv_sec >= timeout) goto too_long;
407 when.tv_sec = timeout;
409 tv_sub(&when, &elapsed, &wake);
411 rcode = select(fd + 1, &fds, NULL, NULL, &wake);
414 RDEBUG("Child PID %u is taking too much time: forcing failure and killing child.", pid);
416 close(fd); /* should give SIGPIPE to child, too */
419 * Clean up the child entry.
421 rad_waitpid(pid, &status);
425 if (errno == EINTR) continue;
431 * Read as many bytes as possible. The kernel
432 * will return the number of bytes available.
435 status = read(fd, answer + done, left);
439 * There's at least 1 byte ready: read it.
441 status = read(fd, answer + done, 1);
444 * Nothing more to read: stop.
451 * Error: See if we have to continue.
455 * We were interrupted: continue reading.
457 if (errno == EINTR) {
462 * There was another error. Most likely
463 * The child process has finished, and
471 if (left <= 0) break;
473 #endif /* __MINGW32__ */
477 /** Execute a program.
479 * @param cmd Command to execute. This is parsed into argv[] parts,
480 * then each individual argv part is xlat'ed.
481 * @param request current request.
482 * @param exec_wait set to 1 if you want to read from or write to child
483 * @param user_msg buffer to append plaintext (non valuepair) output.
484 * @param msg_len length of user_msg buffer.
485 * @param input_pairs list of value pairs - these will be put into
486 * the environment variables of the child.
487 * @param[out] output_pairs list of value pairs - child stdout will be
488 * parsed and added into this list of value pairs.
489 * @param shell_escape
490 * @return 0 if exec_wait==0, exit code if exec_wait!=0, -1 on error.
492 int radius_exec_program(char const *cmd, REQUEST *request,
494 char *user_msg, int msg_len,
495 VALUE_PAIR *input_pairs,
496 VALUE_PAIR **output_pairs,
511 pid = radius_start_program(cmd, request, exec_wait, NULL, &from_child, input_pairs, shell_escape);
520 done = radius_readfrom_program(request, from_child, pid, 10, answer, sizeof(answer));
523 * failure - radius_readfrom_program will
524 * have called close(from_child) for us
526 DEBUG("Failed to read from child output");
534 * Make sure that the writer can't block while writing to
535 * a pipe that no one is reading from anymore.
539 RDEBUG2("Program output is %s", answer);
542 * Parse the output, if any.
548 * For backwards compatibility, first check
549 * for plain text (user_msg).
552 n = userparse(request, answer, &vp);
558 if (n == T_OP_INVALID) {
560 strlcpy(user_msg, answer, msg_len);
564 * HACK: Replace '\n' with ',' so that
565 * userparse() can parse the buffer in
566 * one go (the proper way would be to
567 * fix userparse(), but oh well).
569 for (p = answer; *p; p++) {
571 *p = comma ? ' ' : ',';
575 if (*p == ',') comma++;
579 * Replace any trailing comma by a NUL.
581 if (answer[strlen(answer) - 1] == ',') {
582 answer[strlen(answer) - 1] = '\0';
585 if (userparse(request, answer, &vp) == T_OP_INVALID) {
586 RDEBUGE("Unparsable reply from '%s'", cmd);
590 * Tell the caller about the value
595 } /* else the answer was a set of VP's, not a text message */
596 } /* else we didn't read anything from the child */
599 * Call rad_waitpid (should map to waitpid on non-threaded
600 * or single-server systems).
602 child_pid = rad_waitpid(pid, &status);
603 if (child_pid == 0) {
604 RDEBUGE("Timeout waiting for child");
608 if (child_pid == pid) {
609 if (WIFEXITED(status)) {
610 status = WEXITSTATUS(status);
612 RDEBUGE("Child returned error %d", status);
616 RDEBUG("Child executed successfully");
621 RDEBUGE("Abnormal child exit: %s", strerror(errno));
622 #endif /* __MINGW32__ */
627 static void time_free(void *data)
632 void exec_trigger(REQUEST *request, CONF_SECTION *cs, char const *name, int quench)
642 * Use global "trigger" section if no local config is given.
645 cs = mainconfig.config;
649 * Try to use pair name, rather than reference.
651 attr = strrchr(name, '.');
660 * Find local "trigger" subsection. If it isn't found,
661 * try using the global "trigger" section, and reset the
662 * reference to the full path, rather than the sub-path.
664 subcs = cf_section_sub_find(cs, "trigger");
665 if (!subcs && (cs != mainconfig.config)) {
666 subcs = cf_section_sub_find(mainconfig.config, "trigger");
672 ci = cf_reference_item(subcs, mainconfig.config, attr);
674 RDEBUG3("No such item in trigger section: %s", attr);
678 if (!cf_item_is_pair(ci)) {
679 RDEBUG2("Trigger is not a configuration variable: %s", attr);
683 cp = cf_itemtopair(ci);
686 value = cf_pair_value(cp);
688 RDEBUG2("Trigger has no value: %s", name);
693 * May be called for Status-Server packets.
696 if (request && request->packet) vp = request->packet->vps;
699 * Perform periodic quenching.
704 last_time = cf_data_find(cs, value);
706 last_time = rad_malloc(sizeof(*last_time));
709 if (cf_data_add(cs, value, last_time, time_free) < 0) {
716 * Send the quenched traps at most once per second.
719 time_t now = time(NULL);
720 if (*last_time == now) return;
726 RDEBUG("Trigger %s -> %s", name, value);
727 radius_exec_program(value, request, 0, NULL, 0, vp, NULL, 1);