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  */
10
11#ifndef lint
12static char sccsid[] = "@(#) shell_cmd.c 1.5 94/12/28 17:42:44";
13#endif
14
15/* System libraries. */
16
17#include <sys/types.h>
18#include <sys/param.h>
19#include <sys/wait.h>
20#include <signal.h>
21#include <stdio.h>
22#include <syslog.h>
23#include <string.h>
24#include <unistd.h>
25#include <fcntl.h>
26
27extern void exit();
28
29/* Local stuff. */
30
31#include "tcpd.h"
32
33/* Forward declarations. */
34
35static void do_child(char *command);
36
37/* shell_cmd - execute shell command */
38
39void    shell_cmd(command)
40char   *command;
41{
42    int     child_pid;
43    int     wait_pid;
44
45    /*
46     * Most of the work is done within the child process, to minimize the
47     * risk of damage to the parent.
48     */
49
50    switch (child_pid = fork()) {
51    case -1:					/* error */
52	tcpd_warn("cannot fork: %m");
53	break;
54    case 00:					/* child */
55	do_child(command);
56	/* NOTREACHED */
57    default:					/* parent */
58	while ((wait_pid = wait((int *) 0)) != -1 && wait_pid != child_pid)
59	     /* void */ ;
60    }
61}
62
63/* do_child - exec command with { stdin, stdout, stderr } to /dev/null */
64
65static void do_child(char *command)
66{
67    char   *error;
68    int     tmp_fd;
69
70    /*
71     * Systems with POSIX sessions may send a SIGHUP to grandchildren if the
72     * child exits first. This is sick, sessions were invented for terminals.
73     */
74
75    signal(SIGHUP, SIG_IGN);
76
77    /* Set up new stdin, stdout, stderr, and exec the shell command. */
78
79    for (tmp_fd = 0; tmp_fd < 3; tmp_fd++)
80	(void) close(tmp_fd);
81    if (open("/dev/null", 2) != 0) {
82	error = "open /dev/null: %m";
83    } else if (dup(0) != 1 || dup(0) != 2) {
84	error = "dup: %m";
85    } else {
86	(void) execl("/bin/sh", "sh", "-c", command, (char *) 0);
87	error = "execl /bin/sh: %m";
88    }
89
90    /* Something went wrong. We MUST terminate the child process. */
91
92    tcpd_warn(error);
93    _exit(0);
94}
95