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