Merge branch 'vendor/GCC44'
[dragonfly.git] / contrib / tcp_wrappers / shell_cmd.c
blobdc46f925b0e8c894bec1ff2ec247f15e5d827e2b
1 /*
2 * shell_cmd() takes a shell command after %<character> substitutions. The
3 * command is executed by a /bin/sh child process, with standard input,
4 * standard output and standard error connected to /dev/null.
5 *
6 * Diagnostics are reported through syslog(3).
7 *
8 * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands.
9 */
11 #ifndef lint
12 static char sccsid[] = "@(#) shell_cmd.c 1.5 94/12/28 17:42:44";
13 #endif
15 /* System libraries. */
17 #include <sys/types.h>
18 #include <sys/param.h>
19 #include <signal.h>
20 #include <stdio.h>
21 #include <unistd.h>
22 #include <syslog.h>
23 #include <string.h>
25 extern void exit();
27 /* Local stuff. */
29 #include "tcpd.h"
31 /* Forward declarations. */
33 static void do_child();
35 /* shell_cmd - execute shell command */
37 void shell_cmd(command)
38 char *command;
40 int child_pid;
41 int wait_pid;
44 * Most of the work is done within the child process, to minimize the
45 * risk of damage to the parent.
48 switch (child_pid = fork()) {
49 case -1: /* error */
50 tcpd_warn("cannot fork: %m");
51 break;
52 case 00: /* child */
53 do_child(command);
54 /* NOTREACHED */
55 default: /* parent */
56 while ((wait_pid = wait((int *) 0)) != -1 && wait_pid != child_pid)
57 /* void */ ;
61 /* do_child - exec command with { stdin, stdout, stderr } to /dev/null */
63 static void do_child(command)
64 char *command;
66 char *error;
67 int tmp_fd;
70 * Systems with POSIX sessions may send a SIGHUP to grandchildren if the
71 * child exits first. This is sick, sessions were invented for terminals.
74 signal(SIGHUP, SIG_IGN);
76 /* Set up new stdin, stdout, stderr, and exec the shell command. */
78 for (tmp_fd = 0; tmp_fd < 3; tmp_fd++)
79 (void) close(tmp_fd);
80 if (open("/dev/null", 2) != 0) {
81 error = "open /dev/null: %m";
82 } else if (dup(0) != 1 || dup(0) != 2) {
83 error = "dup: %m";
84 } else {
85 (void) execl("/bin/sh", "sh", "-c", command, (char *) 0);
86 error = "execl /bin/sh: %m";
89 /* Something went wrong. We MUST terminate the child process. */
91 tcpd_warn(error);
92 _exit(0);