Home | History | Annotate | Line # | Download | only in gen
popen.c revision 1.33
      1 /*	$NetBSD: popen.c,v 1.33 2015/01/20 17:28:00 christos Exp $	*/
      2 
      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 #if defined(LIBC_SCCS) && !defined(lint)
     37 #if 0
     38 static char sccsid[] = "@(#)popen.c	8.3 (Berkeley) 5/3/95";
     39 #else
     40 __RCSID("$NetBSD: popen.c,v 1.33 2015/01/20 17:28:00 christos Exp $");
     41 #endif
     42 #endif /* LIBC_SCCS and not lint */
     43 
     44 #include "namespace.h"
     45 #include <sys/param.h>
     46 #include <sys/wait.h>
     47 #include <sys/socket.h>
     48 
     49 #include <assert.h>
     50 #include <errno.h>
     51 #include <paths.h>
     52 #include <signal.h>
     53 #include <stdio.h>
     54 #include <stdlib.h>
     55 #include <string.h>
     56 #include <unistd.h>
     57 #include <fcntl.h>
     58 
     59 #include "env.h"
     60 #include "reentrant.h"
     61 
     62 #ifdef __weak_alias
     63 __weak_alias(popen,_popen)
     64 __weak_alias(pclose,_pclose)
     65 #endif
     66 
     67 static struct pid {
     68 	struct pid *next;
     69 	FILE *fp;
     70 #ifdef _REENTRANT
     71 	int fd;
     72 #endif
     73 	pid_t pid;
     74 } *pidlist;
     75 
     76 #ifdef _REENTRANT
     77 static rwlock_t pidlist_lock = RWLOCK_INITIALIZER;
     78 #endif
     79 
     80 static struct pid *
     81 pdes_get(int *pdes, const char **type)
     82 {
     83 	struct pid *cur;
     84 	int flags = strchr(*type, 'e') ? O_CLOEXEC : 0;
     85 	int serrno;
     86 
     87 	if (strchr(*type, '+')) {
     88 		int stype = flags ? (SOCK_STREAM | SOCK_CLOEXEC) : SOCK_STREAM;
     89 		*type = "r+";
     90 		if (socketpair(AF_LOCAL, stype, 0, pdes) < 0)
     91 			return NULL;
     92 	} else  {
     93 		*type = strrchr(*type, 'r') ? "r" : "w";
     94 		if (pipe2(pdes, flags) == -1)
     95 			return NULL;
     96 	}
     97 
     98 	if ((cur = malloc(sizeof(*cur))) != NULL)
     99 		return cur;
    100 	serrno = errno;
    101 	(void)close(pdes[0]);
    102 	(void)close(pdes[1]);
    103 	errno = serrno;
    104 	return NULL;
    105 }
    106 
    107 static void
    108 pdes_child(int *pdes, const char *type)
    109 {
    110 	struct pid *old;
    111 
    112 	/* POSIX.2 B.3.2.2 "popen() shall ensure that any streams
    113 	   from previous popen() calls that remain open in the
    114 	   parent process are closed in the new child process. */
    115 	for (old = pidlist; old; old = old->next)
    116 #ifdef _REENTRANT
    117 		(void)close(old->fd); /* don't allow a flush */
    118 #else
    119 		(void)close(fileno(old->fp)); /* don't allow a flush */
    120 #endif
    121 
    122 	if (type[0] == 'r') {
    123 		(void)close(pdes[0]);
    124 		if (pdes[1] != STDOUT_FILENO) {
    125 			(void)dup2(pdes[1], STDOUT_FILENO);
    126 			(void)close(pdes[1]);
    127 		}
    128 		if (type[1] == '+')
    129 			(void)dup2(STDOUT_FILENO, STDIN_FILENO);
    130 	} else {
    131 		(void)close(pdes[1]);
    132 		if (pdes[0] != STDIN_FILENO) {
    133 			(void)dup2(pdes[0], STDIN_FILENO);
    134 			(void)close(pdes[0]);
    135 		}
    136 	}
    137 }
    138 
    139 static void
    140 pdes_parent(int *pdes, struct pid *cur, pid_t pid, const char *type)
    141 {
    142 	FILE *iop;
    143 
    144 	/* Parent; assume fdopen can't fail. */
    145 	if (*type == 'r') {
    146 		iop = fdopen(pdes[0], type);
    147 #ifdef _REENTRANT
    148 		cur->fd = pdes[0];
    149 #endif
    150 		(void)close(pdes[1]);
    151 	} else {
    152 		iop = fdopen(pdes[1], type);
    153 #ifdef _REENTRANT
    154 		cur->fd = pdes[1];
    155 #endif
    156 		(void)close(pdes[0]);
    157 	}
    158 
    159 	/* Link into list of file descriptors. */
    160 	cur->fp = iop;
    161 	cur->pid =  pid;
    162 	cur->next = pidlist;
    163 	pidlist = cur;
    164 }
    165 
    166 static void
    167 pdes_error(int *pdes, struct pid *cur)
    168 {
    169 	free(cur);
    170 	(void)close(pdes[0]);
    171 	(void)close(pdes[1]);
    172 }
    173 
    174 FILE *
    175 popen(const char *cmd, const char *type)
    176 {
    177 	struct pid *cur;
    178 	int pdes[2], serrno;
    179 	pid_t pid;
    180 
    181 	_DIAGASSERT(cmd != NULL);
    182 	_DIAGASSERT(type != NULL);
    183 
    184 	if ((cur = pdes_get(pdes, &type)) == NULL)
    185 		return NULL;
    186 
    187 #ifdef _REENTRANT
    188 	(void)rwlock_rdlock(&pidlist_lock);
    189 #endif
    190 	(void)__readlockenv();
    191 	switch (pid = vfork()) {
    192 	case -1:			/* Error. */
    193 		serrno = errno;
    194 		(void)__unlockenv();
    195 #ifdef _REENTRANT
    196 		(void)rwlock_unlock(&pidlist_lock);
    197 #endif
    198 		errno = serrno;
    199 		return NULL;
    200 		/* NOTREACHED */
    201 	case 0:				/* Child. */
    202 		pdes_child(pdes, type);
    203 		execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
    204 		_exit(127);
    205 		/* NOTREACHED */
    206 	}
    207 	(void)__unlockenv();
    208 
    209 	pdes_parent(pdes, cur, pid, type);
    210 
    211 #ifdef _REENTRANT
    212 	(void)rwlock_unlock(&pidlist_lock);
    213 #endif
    214 
    215 	return cur->fp;
    216 }
    217 
    218 FILE *
    219 popenve(const char *cmd, char *const *argv, char *const *envp, const char *type)
    220 {
    221 	struct pid *cur;
    222 	int pdes[2], serrno;
    223 	pid_t pid;
    224 
    225 	_DIAGASSERT(cmd != NULL);
    226 	_DIAGASSERT(type != NULL);
    227 
    228 	if ((cur = pdes_get(pdes, &type)) == NULL)
    229 		return NULL;
    230 
    231 #ifdef _REENTRANT
    232 	(void)rwlock_rdlock(&pidlist_lock);
    233 #endif
    234 	switch (pid = vfork()) {
    235 	case -1:			/* Error. */
    236 		serrno = errno;
    237 #ifdef _REENTRANT
    238 		(void)rwlock_unlock(&pidlist_lock);
    239 #endif
    240 		pdes_error(pdes, cur);
    241 		errno = serrno;
    242 		return NULL;
    243 		/* NOTREACHED */
    244 	case 0:				/* Child. */
    245 		pdes_child(pdes, type);
    246 		execve(cmd, argv, envp);
    247 		_exit(127);
    248 		/* NOTREACHED */
    249 	}
    250 
    251 	pdes_parent(pdes, cur, pid, type);
    252 
    253 #ifdef _REENTRANT
    254 	(void)rwlock_unlock(&pidlist_lock);
    255 #endif
    256 
    257 	return cur->fp;
    258 }
    259 
    260 /*
    261  * pclose --
    262  *	Pclose returns -1 if stream is not associated with a `popened' command,
    263  *	if already `pclosed', or waitpid returns an error.
    264  */
    265 int
    266 pclose(FILE *iop)
    267 {
    268 	struct pid *cur, *last;
    269 	int pstat;
    270 	pid_t pid;
    271 
    272 	_DIAGASSERT(iop != NULL);
    273 
    274 #ifdef _REENTRANT
    275 	rwlock_wrlock(&pidlist_lock);
    276 #endif
    277 
    278 	/* Find the appropriate file pointer. */
    279 	for (last = NULL, cur = pidlist; cur; last = cur, cur = cur->next)
    280 		if (cur->fp == iop)
    281 			break;
    282 	if (cur == NULL) {
    283 #ifdef _REENTRANT
    284 		(void)rwlock_unlock(&pidlist_lock);
    285 #endif
    286 		errno = ESRCH;
    287 		return -1;
    288 	}
    289 
    290 	(void)fclose(iop);
    291 
    292 	/* Remove the entry from the linked list. */
    293 	if (last == NULL)
    294 		pidlist = cur->next;
    295 	else
    296 		last->next = cur->next;
    297 
    298 #ifdef _REENTRANT
    299 	(void)rwlock_unlock(&pidlist_lock);
    300 #endif
    301 
    302 	do {
    303 		pid = waitpid(cur->pid, &pstat, 0);
    304 	} while (pid == -1 && errno == EINTR);
    305 
    306 	free(cur);
    307 
    308 	return pid == -1 ? -1 : pstat;
    309 }
    310