xref: /illumos-gate/usr/src/lib/libc/port/stdio/system.c (revision a51287096c163d49f314be2853367563999e083c)
1  /*
2   * CDDL HEADER START
3   *
4   * The contents of this file are subject to the terms of the
5   * Common Development and Distribution License (the "License").
6   * You may not use this file except in compliance with the License.
7   *
8   * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9   * or http://www.opensolaris.org/os/licensing.
10   * See the License for the specific language governing permissions
11   * and limitations under the License.
12   *
13   * When distributing Covered Code, include this CDDL HEADER in each
14   * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15   * If applicable, add the following below this CDDL HEADER, with the
16   * fields enclosed by brackets "[]" replaced with your own identifying
17   * information: Portions Copyright [yyyy] [name of copyright owner]
18   *
19   * CDDL HEADER END
20   */
21  
22  /*
23   * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24   * Use is subject to license terms.
25   */
26  
27  /*	Copyright (c) 1988 AT&T	*/
28  /*	  All Rights Reserved  	*/
29  
30  #include "lint.h"
31  #include "mtlib.h"
32  #include <sys/types.h>
33  #include <sys/wait.h>
34  #include <signal.h>
35  #include <stdlib.h>
36  #include <wait.h>
37  #include <sys/stat.h>
38  #include <unistd.h>
39  #include <memory.h>
40  #include <thread.h>
41  #include <pthread.h>
42  #include <errno.h>
43  #include <synch.h>
44  #include <spawn.h>
45  #include "libc.h"
46  
47  extern const char **_environ;
48  
49  extern int __xpg4;	/* defined in _xpg4.c; 0 if not xpg4-compiled program */
50  extern const sigset_t maskset;		/* all maskable signals */
51  
52  static mutex_t sys_lock = DEFAULTMUTEX;	/* protects the following */
53  static uint_t sys_count = 0;		/* number of threads in system() */
54  static struct sigaction sys_ibuf;	/* saved SIGINT sigaction */
55  static struct sigaction sys_qbuf;	/* saved SIGQUIT sigaction */
56  static struct sigaction ignore = {0, {SIG_IGN}, {0}};
57  
58  /*
59   * Things needed by the cancellation cleanup handler.
60   */
61  typedef struct {
62  	sigset_t	savemask;	/* saved signal mask */
63  	pid_t		pid;		/* if nonzero, the child's pid */
64  } cleanup_t;
65  
66  /*
67   * Daemon thread whose sole function is to reap an abandoned child.
68   * Also invoked from pclose() (see port/stdio/popen.c).
69   */
70  void *
71  reapchild(void *arg)
72  {
73  	pid_t pid = (pid_t)(uintptr_t)arg;
74  	int cancel_state;
75  
76  	(void) pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cancel_state);
77  	while (waitpid(pid, NULL, 0) == -1) {
78  		if (errno != EINTR)
79  			break;
80  	}
81  	(void) pthread_setcancelstate(cancel_state, NULL);
82  	return (NULL);
83  }
84  
85  /*
86   * Cancellation cleanup handler.
87   * If we were cancelled in waitpid(), create a daemon thread to
88   * reap our abandoned child.  No other thread can do this for us.
89   * It would be better if there were a system call to disinherit
90   * a child process (give it to init, just as though we exited).
91   */
92  static void
93  cleanup(void *arg)
94  {
95  	cleanup_t *cup = arg;
96  
97  	if (cup->pid != 0) {	/* we were cancelled; abandoning our pid */
98  		(void) thr_sigsetmask(SIG_SETMASK, &maskset, NULL);
99  		(void) thr_create(NULL, 0,
100  		    reapchild, (void *)(uintptr_t)cup->pid,
101  		    THR_DAEMON, NULL);
102  	}
103  
104  	lmutex_lock(&sys_lock);
105  	if (--sys_count == 0) {		/* leaving system() */
106  		/*
107  		 * There are no remaining threads in system(), so
108  		 * restore the SIGINT and SIGQUIT signal actions.
109  		 */
110  		(void) sigaction(SIGINT, &sys_ibuf, NULL);
111  		(void) sigaction(SIGQUIT, &sys_qbuf, NULL);
112  	}
113  	lmutex_unlock(&sys_lock);
114  
115  	(void) thr_sigsetmask(SIG_SETMASK, &cup->savemask, NULL);
116  }
117  
118  int
119  system(const char *cmd)
120  {
121  	cleanup_t cu;
122  	pid_t w;
123  	int status;
124  	int error;
125  	sigset_t mask;
126  	struct stat64 buf;
127  	const char *shpath;
128  	char *argv[4];
129  	posix_spawnattr_t attr;
130  	static const char *sun_path = "/bin/sh";
131  	static const char *xpg4_path = "/usr/xpg4/bin/sh";
132  	static const char *shell = "sh";
133  
134  	shpath = __xpg4? xpg4_path : sun_path;
135  
136  	if (cmd == NULL) {
137  		if (stat64(shpath, &buf) != 0) {
138  			return (0);
139  		} else if (getuid() == buf.st_uid) {
140  			/* exec for user */
141  			if ((buf.st_mode & 0100) == 0)
142  				return (0);
143  		} else if (getgid() == buf.st_gid) {
144  			/* exec for group */
145  			if ((buf.st_mode & 0010) == 0)
146  				return (0);
147  		} else if ((buf.st_mode & 0001) == 0) {	/* exec for others */
148  			return (0);
149  		}
150  		return (1);
151  	}
152  
153  	/*
154  	 * Initialize the posix_spawn() attributes structure.
155  	 *
156  	 * The setting of POSIX_SPAWN_WAITPID_NP ensures that no
157  	 * wait-for-multiple wait() operation will reap our child
158  	 * and that the child will not be automatically reaped due
159  	 * to the disposition of SIGCHLD being set to be ignored.
160  	 * Only a specific wait for the specific pid will be able
161  	 * to reap the child.  Since no other thread knows the pid
162  	 * of our child, this should be safe enough.
163  	 *
164  	 * The POSIX_SPAWN_NOEXECERR_NP flag tells posix_spawn() not
165  	 * to fail if the shell cannot be executed, but rather cause
166  	 * a child to be created that simply performs _exit(127).
167  	 * This is in order to satisfy the Posix requirement on system():
168  	 *	The system function shall behave as if a child process were
169  	 *	created using fork(), and the child process invoked the sh
170  	 *	utility using execl().  If some error prevents the command
171  	 *	language interpreter from executing after the child process
172  	 *	is created, the return value from system() shall be as if
173  	 *	the command language interpreter had terminated using
174  	 *	exit(127) or _exit(127).
175  	 */
176  	error = posix_spawnattr_init(&attr);
177  	if (error == 0)
178  		error = posix_spawnattr_setflags(&attr,
179  		    POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF |
180  		    POSIX_SPAWN_NOSIGCHLD_NP | POSIX_SPAWN_WAITPID_NP |
181  		    POSIX_SPAWN_NOEXECERR_NP);
182  
183  	/*
184  	 * The POSIX spec for system() requires us to block SIGCHLD,
185  	 * the rationale being that the process's signal handler for
186  	 * SIGCHLD, if any, should not be called when our child exits.
187  	 * This doesn't work for a multithreaded process because some
188  	 * other thread could receive the SIGCHLD.
189  	 *
190  	 * The above setting of POSIX_SPAWN_NOSIGCHLD_NP ensures that no
191  	 * SIGCHLD signal will be posted for our child when it exits, so
192  	 * we don't have to block SIGCHLD to meet the intent of the spec.
193  	 * We block SIGCHLD anyway, just because the spec requires it.
194  	 */
195  	(void) sigemptyset(&mask);
196  	(void) sigaddset(&mask, SIGCHLD);
197  	(void) thr_sigsetmask(SIG_BLOCK, &mask, &cu.savemask);
198  	/*
199  	 * Tell posix_spawn() to restore the signal mask in the child.
200  	 */
201  	if (error == 0)
202  		error = posix_spawnattr_setsigmask(&attr, &cu.savemask);
203  
204  	/*
205  	 * We are required to set the disposition of SIGINT and SIGQUIT
206  	 * to be ignored for the duration of the system() operation.
207  	 *
208  	 * We allow more than one thread to call system() concurrently by
209  	 * keeping a count of such threads.  The signal actions are set
210  	 * to SIG_IGN when the first thread calls system().  They are
211  	 * restored in cleanup() when the last thread exits system().
212  	 *
213  	 * However, system() is still MT-unsafe because sigaction() has
214  	 * a process-wide effect and some other thread may also be
215  	 * setting the signal actions for SIGINT or SIGQUIT.
216  	 */
217  	lmutex_lock(&sys_lock);
218  	if (sys_count++ == 0) {
219  		(void) sigaction(SIGINT, &ignore, &sys_ibuf);
220  		(void) sigaction(SIGQUIT, &ignore, &sys_qbuf);
221  	}
222  	lmutex_unlock(&sys_lock);
223  
224  	/*
225  	 * If SIGINT and SIGQUIT were not already SIG_IGN, tell
226  	 * posix_spawn() to make them SIG_DFL in the child,
227  	 * else leave them as SIG_IGN in the child.
228  	 */
229  	(void) sigemptyset(&mask);
230  	if (sys_ibuf.sa_handler != SIG_IGN)
231  		(void) sigaddset(&mask, SIGINT);
232  	if (sys_qbuf.sa_handler != SIG_IGN)
233  		(void) sigaddset(&mask, SIGQUIT);
234  	if (error == 0)
235  		error = posix_spawnattr_setsigdefault(&attr, &mask);
236  
237  	argv[0] = (char *)shell;
238  	argv[1] = "-c";
239  	argv[2] = (char *)cmd;
240  	argv[3] = NULL;
241  	if (error == 0)
242  		error = posix_spawn(&cu.pid, shpath, NULL, &attr,
243  		    (char *const *)argv, (char *const *)_environ);
244  
245  	(void) posix_spawnattr_destroy(&attr);
246  
247  	if (error) {
248  		errno = error;
249  		status = -1;
250  	} else {
251  		/*
252  		 * system() is a cancellation point and so is waitpid().
253  		 */
254  		pthread_cleanup_push(cleanup, &cu);
255  		do {
256  			w = waitpid(cu.pid, &status, 0);
257  		} while (w == -1 && errno == EINTR);
258  		pthread_cleanup_pop(0);
259  		if (w == -1)
260  			status = -1;
261  	}
262  	error = errno;
263  	cu.pid = 0;
264  	cleanup(&cu);
265  	errno = error;
266  
267  	return (status);
268  }
269