xref: /freebsd/lib/libc/gen/popen.c (revision eb69d1f144a6fcc765d1b9d44a5ae8082353e70b)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1988, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software written by Ken Arnold and
8  * published in UNIX Review, Vol. 6, No. 8.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #if defined(LIBC_SCCS) && !defined(lint)
36 static char sccsid[] = "@(#)popen.c	8.3 (Berkeley) 5/3/95";
37 #endif /* LIBC_SCCS and not lint */
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 #include "namespace.h"
42 #include <sys/param.h>
43 #include <sys/queue.h>
44 #include <sys/wait.h>
45 
46 #include <signal.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <unistd.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <paths.h>
54 #include <pthread.h>
55 #include "un-namespace.h"
56 #include "libc_private.h"
57 
58 extern char **environ;
59 
60 struct pid {
61 	SLIST_ENTRY(pid) next;
62 	FILE *fp;
63 	pid_t pid;
64 };
65 static SLIST_HEAD(, pid) pidlist = SLIST_HEAD_INITIALIZER(pidlist);
66 static pthread_mutex_t pidlist_mutex = PTHREAD_MUTEX_INITIALIZER;
67 
68 #define	THREAD_LOCK()	if (__isthreaded) _pthread_mutex_lock(&pidlist_mutex)
69 #define	THREAD_UNLOCK()	if (__isthreaded) _pthread_mutex_unlock(&pidlist_mutex)
70 
71 FILE *
72 popen(const char *command, const char *type)
73 {
74 	struct pid *cur;
75 	FILE *iop;
76 	int pdes[2], pid, twoway, cloexec;
77 	int pdes_unused_in_parent;
78 	char *argv[4];
79 	struct pid *p;
80 
81 	cloexec = strchr(type, 'e') != NULL;
82 	/*
83 	 * Lite2 introduced two-way popen() pipes using _socketpair().
84 	 * FreeBSD's pipe() is bidirectional, so we use that.
85 	 */
86 	if (strchr(type, '+')) {
87 		twoway = 1;
88 		type = "r+";
89 	} else  {
90 		twoway = 0;
91 		if ((*type != 'r' && *type != 'w') ||
92 		    (type[1] && (type[1] != 'e' || type[2])))
93 			return (NULL);
94 	}
95 	if (pipe2(pdes, O_CLOEXEC) < 0)
96 		return (NULL);
97 
98 	if ((cur = malloc(sizeof(struct pid))) == NULL) {
99 		(void)_close(pdes[0]);
100 		(void)_close(pdes[1]);
101 		return (NULL);
102 	}
103 
104 	if (*type == 'r') {
105 		iop = fdopen(pdes[0], type);
106 		pdes_unused_in_parent = pdes[1];
107 	} else {
108 		iop = fdopen(pdes[1], type);
109 		pdes_unused_in_parent = pdes[0];
110 	}
111 	if (iop == NULL) {
112 		(void)_close(pdes[0]);
113 		(void)_close(pdes[1]);
114 		free(cur);
115 		return (NULL);
116 	}
117 
118 	argv[0] = "sh";
119 	argv[1] = "-c";
120 	argv[2] = (char *)command;
121 	argv[3] = NULL;
122 
123 	THREAD_LOCK();
124 	switch (pid = vfork()) {
125 	case -1:			/* Error. */
126 		THREAD_UNLOCK();
127 		/*
128 		 * The _close() closes the unused end of pdes[], while
129 		 * the fclose() closes the used end of pdes[], *and* cleans
130 		 * up iop.
131 		 */
132 		(void)_close(pdes_unused_in_parent);
133 		free(cur);
134 		(void)fclose(iop);
135 		return (NULL);
136 		/* NOTREACHED */
137 	case 0:				/* Child. */
138 		if (*type == 'r') {
139 			/*
140 			 * The _dup2() to STDIN_FILENO is repeated to avoid
141 			 * writing to pdes[1], which might corrupt the
142 			 * parent's copy.  This isn't good enough in
143 			 * general, since the _exit() is no return, so
144 			 * the compiler is free to corrupt all the local
145 			 * variables.
146 			 */
147 			if (pdes[1] != STDOUT_FILENO) {
148 				(void)_dup2(pdes[1], STDOUT_FILENO);
149 				if (twoway)
150 					(void)_dup2(STDOUT_FILENO, STDIN_FILENO);
151 			} else if (twoway && (pdes[1] != STDIN_FILENO)) {
152 				(void)_dup2(pdes[1], STDIN_FILENO);
153 				(void)_fcntl(pdes[1], F_SETFD, 0);
154 			} else
155 				(void)_fcntl(pdes[1], F_SETFD, 0);
156 		} else {
157 			if (pdes[0] != STDIN_FILENO) {
158 				(void)_dup2(pdes[0], STDIN_FILENO);
159 			} else
160 				(void)_fcntl(pdes[0], F_SETFD, 0);
161 		}
162 		SLIST_FOREACH(p, &pidlist, next)
163 			(void)_close(fileno(p->fp));
164 		_execve(_PATH_BSHELL, argv, environ);
165 		_exit(127);
166 		/* NOTREACHED */
167 	}
168 	THREAD_UNLOCK();
169 
170 	/* Parent. */
171 	(void)_close(pdes_unused_in_parent);
172 
173 	/* Link into list of file descriptors. */
174 	cur->fp = iop;
175 	cur->pid = pid;
176 	THREAD_LOCK();
177 	SLIST_INSERT_HEAD(&pidlist, cur, next);
178 	THREAD_UNLOCK();
179 
180 	/*
181 	 * To guard against undesired fd passing with concurrent calls,
182 	 * only clear the close-on-exec flag after linking the file into
183 	 * the list which will cause an explicit close.
184 	 */
185 	if (!cloexec)
186 		(void)_fcntl(*type == 'r' ? pdes[0] : pdes[1], F_SETFD, 0);
187 
188 	return (iop);
189 }
190 
191 /*
192  * pclose --
193  *	Pclose returns -1 if stream is not associated with a `popened' command,
194  *	if already `pclosed', or waitpid returns an error.
195  */
196 int
197 pclose(FILE *iop)
198 {
199 	struct pid *cur, *last = NULL;
200 	int pstat;
201 	pid_t pid;
202 
203 	/*
204 	 * Find the appropriate file pointer and remove it from the list.
205 	 */
206 	THREAD_LOCK();
207 	SLIST_FOREACH(cur, &pidlist, next) {
208 		if (cur->fp == iop)
209 			break;
210 		last = cur;
211 	}
212 	if (cur == NULL) {
213 		THREAD_UNLOCK();
214 		return (-1);
215 	}
216 	if (last == NULL)
217 		SLIST_REMOVE_HEAD(&pidlist, next);
218 	else
219 		SLIST_REMOVE_AFTER(last, next);
220 	THREAD_UNLOCK();
221 
222 	(void)fclose(iop);
223 
224 	do {
225 		pid = _wait4(cur->pid, &pstat, 0, (struct rusage *)0);
226 	} while (pid == -1 && errno == EINTR);
227 
228 	free(cur);
229 
230 	return (pid == -1 ? -1 : pstat);
231 }
232