xref: /illumos-gate/usr/src/lib/libwrap/shell_cmd.c (revision b02947bf393d39f68e6c7fa8ccb98688f7f9c407)
1 /*
2  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6  /*
7   * shell_cmd() takes a shell command after %<character> substitutions. The
8   * command is executed by a /bin/sh child process, with standard input,
9   * standard output and standard error connected to /dev/null.
10   *
11   * Diagnostics are reported through syslog(3).
12   *
13   * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands.
14   */
15 
16 #ifndef lint
17 static char sccsid[] = "@(#) shell_cmd.c 1.5 94/12/28 17:42:44";
18 #endif
19 
20 /* System libraries. */
21 
22 #include <sys/types.h>
23 #include <sys/param.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <wait.h>
29 #include <fcntl.h>
30 #include <syslog.h>
31 #include <string.h>
32 
33 extern void exit();
34 
35 /* Local stuff. */
36 
37 #include "tcpd.h"
38 
39 /* Forward declarations. */
40 
41 static void do_child();
42 
43 /* shell_cmd - execute shell command */
44 
45 void    shell_cmd(command)
46 char   *command;
47 {
48     int     child_pid;
49     int     wait_pid;
50 
51     /*
52      * Most of the work is done within the child process, to minimize the
53      * risk of damage to the parent.
54      */
55 
56     switch (child_pid = fork()) {
57     case -1:					/* error */
58 	tcpd_warn("cannot fork: %m");
59 	break;
60     case 00:					/* child */
61 	do_child(command);
62 	/* NOTREACHED */
63     default:					/* parent */
64 	while ((wait_pid = wait((int *) 0)) != -1 && wait_pid != child_pid)
65 	     /* void */ ;
66     }
67 }
68 
69 /* do_child - exec command with { stdin, stdout, stderr } to /dev/null */
70 
71 static void do_child(command)
72 char   *command;
73 {
74     char   *error;
75     int     tmp_fd;
76 
77     /*
78      * Systems with POSIX sessions may send a SIGHUP to grandchildren if the
79      * child exits first. This is sick, sessions were invented for terminals.
80      */
81 
82     signal(SIGHUP, SIG_IGN);
83 
84     /* Set up new stdin, stdout, stderr, and exec the shell command. */
85 
86     for (tmp_fd = 0; tmp_fd < 3; tmp_fd++)
87 	(void) close(tmp_fd);
88     if (open("/dev/null", 2) != 0) {
89 	error = "open /dev/null: %m";
90     } else if (dup(0) != 1 || dup(0) != 2) {
91 	error = "dup: %m";
92     } else {
93 	(void) execl("/bin/sh", "sh", "-c", command, (char *) 0);
94 	error = "execl /bin/sh: %m";
95     }
96 
97     /* Something went wrong. We MUST terminate the child process. */
98 
99     tcpd_warn(error);
100     _exit(0);
101 }
102