xref: /freebsd/lib/libc/gen/popen.c (revision 4d846d26)
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 #include <sys/cdefs.h>
36 __SCCSID("@(#)popen.c	8.3 (Berkeley) 5/3/95");
37 __FBSDID("$FreeBSD$");
38 
39 #include "namespace.h"
40 #include <sys/param.h>
41 #include <sys/queue.h>
42 #include <sys/wait.h>
43 
44 #include <signal.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <unistd.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <paths.h>
52 #include <pthread.h>
53 #include "un-namespace.h"
54 #include "libc_private.h"
55 
56 struct pid {
57 	SLIST_ENTRY(pid) next;
58 	FILE *fp;
59 	pid_t pid;
60 };
61 static SLIST_HEAD(, pid) pidlist = SLIST_HEAD_INITIALIZER(pidlist);
62 static pthread_mutex_t pidlist_mutex = PTHREAD_MUTEX_INITIALIZER;
63 
64 #define	THREAD_LOCK()	if (__isthreaded) _pthread_mutex_lock(&pidlist_mutex)
65 #define	THREAD_UNLOCK()	if (__isthreaded) _pthread_mutex_unlock(&pidlist_mutex)
66 
67 FILE *
68 popen(const char *command, const char *type)
69 {
70 	struct pid *cur;
71 	FILE *iop;
72 	int pdes[2], pid, twoway, cloexec;
73 	int pdes_unused_in_parent;
74 	char *argv[4];
75 	struct pid *p;
76 
77 	cloexec = strchr(type, 'e') != NULL;
78 	/*
79 	 * Lite2 introduced two-way popen() pipes using _socketpair().
80 	 * FreeBSD's pipe() is bidirectional, so we use that.
81 	 */
82 	if (strchr(type, '+')) {
83 		twoway = 1;
84 		type = "r+";
85 	} else  {
86 		twoway = 0;
87 		if ((*type != 'r' && *type != 'w') ||
88 		    (type[1] && (type[1] != 'e' || type[2])))
89 			return (NULL);
90 	}
91 	if (pipe2(pdes, O_CLOEXEC) < 0)
92 		return (NULL);
93 
94 	if ((cur = malloc(sizeof(struct pid))) == NULL) {
95 		(void)_close(pdes[0]);
96 		(void)_close(pdes[1]);
97 		return (NULL);
98 	}
99 
100 	if (*type == 'r') {
101 		iop = fdopen(pdes[0], type);
102 		pdes_unused_in_parent = pdes[1];
103 	} else {
104 		iop = fdopen(pdes[1], type);
105 		pdes_unused_in_parent = pdes[0];
106 	}
107 	if (iop == NULL) {
108 		(void)_close(pdes[0]);
109 		(void)_close(pdes[1]);
110 		free(cur);
111 		return (NULL);
112 	}
113 
114 	argv[0] = "sh";
115 	argv[1] = "-c";
116 	argv[2] = (char *)command;
117 	argv[3] = NULL;
118 
119 	THREAD_LOCK();
120 	switch (pid = vfork()) {
121 	case -1:			/* Error. */
122 		THREAD_UNLOCK();
123 		/*
124 		 * The _close() closes the unused end of pdes[], while
125 		 * the fclose() closes the used end of pdes[], *and* cleans
126 		 * up iop.
127 		 */
128 		(void)_close(pdes_unused_in_parent);
129 		free(cur);
130 		(void)fclose(iop);
131 		return (NULL);
132 		/* NOTREACHED */
133 	case 0:				/* Child. */
134 		if (*type == 'r') {
135 			/*
136 			 * The _dup2() to STDIN_FILENO is repeated to avoid
137 			 * writing to pdes[1], which might corrupt the
138 			 * parent's copy.  This isn't good enough in
139 			 * general, since the _exit() is no return, so
140 			 * the compiler is free to corrupt all the local
141 			 * variables.
142 			 */
143 			if (pdes[1] != STDOUT_FILENO) {
144 				(void)_dup2(pdes[1], STDOUT_FILENO);
145 				if (twoway)
146 					(void)_dup2(STDOUT_FILENO, STDIN_FILENO);
147 			} else if (twoway && (pdes[1] != STDIN_FILENO)) {
148 				(void)_dup2(pdes[1], STDIN_FILENO);
149 				(void)_fcntl(pdes[1], F_SETFD, 0);
150 			} else
151 				(void)_fcntl(pdes[1], F_SETFD, 0);
152 		} else {
153 			if (pdes[0] != STDIN_FILENO) {
154 				(void)_dup2(pdes[0], STDIN_FILENO);
155 			} else
156 				(void)_fcntl(pdes[0], F_SETFD, 0);
157 		}
158 		SLIST_FOREACH(p, &pidlist, next)
159 			(void)_close(fileno(p->fp));
160 		_execve(_PATH_BSHELL, argv, environ);
161 		_exit(127);
162 		/* NOTREACHED */
163 	}
164 	THREAD_UNLOCK();
165 
166 	/* Parent. */
167 	(void)_close(pdes_unused_in_parent);
168 
169 	/* Link into list of file descriptors. */
170 	cur->fp = iop;
171 	cur->pid = pid;
172 	THREAD_LOCK();
173 	SLIST_INSERT_HEAD(&pidlist, cur, next);
174 	THREAD_UNLOCK();
175 
176 	/*
177 	 * To guard against undesired fd passing with concurrent calls,
178 	 * only clear the close-on-exec flag after linking the file into
179 	 * the list which will cause an explicit close.
180 	 */
181 	if (!cloexec)
182 		(void)_fcntl(fileno(iop), F_SETFD, 0);
183 
184 	return (iop);
185 }
186 
187 /*
188  * pclose --
189  *	Pclose returns -1 if stream is not associated with a `popened' command,
190  *	if already `pclosed', or waitpid returns an error.
191  */
192 int
193 pclose(FILE *iop)
194 {
195 	struct pid *cur, *last = NULL;
196 	int pstat;
197 	pid_t pid;
198 
199 	/*
200 	 * Find the appropriate file pointer and remove it from the list.
201 	 */
202 	THREAD_LOCK();
203 	SLIST_FOREACH(cur, &pidlist, next) {
204 		if (cur->fp == iop)
205 			break;
206 		last = cur;
207 	}
208 	if (cur == NULL) {
209 		THREAD_UNLOCK();
210 		return (-1);
211 	}
212 	if (last == NULL)
213 		SLIST_REMOVE_HEAD(&pidlist, next);
214 	else
215 		SLIST_REMOVE_AFTER(last, next);
216 	THREAD_UNLOCK();
217 
218 	(void)fclose(iop);
219 
220 	do {
221 		pid = _wait4(cur->pid, &pstat, 0, (struct rusage *)0);
222 	} while (pid == -1 && errno == EINTR);
223 
224 	free(cur);
225 
226 	return (pid == -1 ? -1 : pstat);
227 }
228