Home | History | Annotate | Line # | Download | only in sh
redir.c revision 1.24
      1 /*	$NetBSD: redir.c,v 1.24 2002/09/27 18:56:55 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Kenneth Almquist.
      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. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the University of
     21  *	California, Berkeley and its contributors.
     22  * 4. Neither the name of the University nor the names of its contributors
     23  *    may be used to endorse or promote products derived from this software
     24  *    without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     36  * SUCH DAMAGE.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 #ifndef lint
     41 #if 0
     42 static char sccsid[] = "@(#)redir.c	8.2 (Berkeley) 5/4/95";
     43 #else
     44 __RCSID("$NetBSD: redir.c,v 1.24 2002/09/27 18:56:55 christos Exp $");
     45 #endif
     46 #endif /* not lint */
     47 
     48 #include <sys/types.h>
     49 #include <sys/param.h>	/* PIPE_BUF */
     50 #include <signal.h>
     51 #include <string.h>
     52 #include <fcntl.h>
     53 #include <errno.h>
     54 #include <unistd.h>
     55 #include <stdlib.h>
     56 
     57 /*
     58  * Code for dealing with input/output redirection.
     59  */
     60 
     61 #include "shell.h"
     62 #include "nodes.h"
     63 #include "jobs.h"
     64 #include "options.h"
     65 #include "expand.h"
     66 #include "redir.h"
     67 #include "output.h"
     68 #include "memalloc.h"
     69 #include "error.h"
     70 
     71 
     72 #define EMPTY -2		/* marks an unused slot in redirtab */
     73 #ifndef PIPE_BUF
     74 # define PIPESIZE 4096		/* amount of buffering in a pipe */
     75 #else
     76 # define PIPESIZE PIPE_BUF
     77 #endif
     78 
     79 
     80 MKINIT
     81 struct redirtab {
     82 	struct redirtab *next;
     83 	short renamed[10];
     84 };
     85 
     86 
     87 MKINIT struct redirtab *redirlist;
     88 
     89 /*
     90  * We keep track of whether or not fd0 has been redirected.  This is for
     91  * background commands, where we want to redirect fd0 to /dev/null only
     92  * if it hasn't already been redirected.
     93 */
     94 int fd0_redirected = 0;
     95 
     96 STATIC void openredirect __P((union node *, char[10 ]));
     97 STATIC int openhere __P((union node *));
     98 
     99 
    100 /*
    101  * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
    102  * old file descriptors are stashed away so that the redirection can be
    103  * undone by calling popredir.  If the REDIR_BACKQ flag is set, then the
    104  * standard output, and the standard error if it becomes a duplicate of
    105  * stdout, is saved in memory.
    106  */
    107 
    108 void
    109 redirect(redir, flags)
    110 	union node *redir;
    111 	int flags;
    112 	{
    113 	union node *n;
    114 	struct redirtab *sv = NULL;
    115 	int i;
    116 	int fd;
    117 	int try;
    118 	char memory[10];	/* file descriptors to write to memory */
    119 
    120 	for (i = 10 ; --i >= 0 ; )
    121 		memory[i] = 0;
    122 	memory[1] = flags & REDIR_BACKQ;
    123 	if (flags & REDIR_PUSH) {
    124 		/* We don't have to worry about REDIR_VFORK here, as
    125 		 * flags & REDIR_PUSH is never true if REDIR_VFORK is set.
    126 		 */
    127 		sv = ckmalloc(sizeof (struct redirtab));
    128 		for (i = 0 ; i < 10 ; i++)
    129 			sv->renamed[i] = EMPTY;
    130 		sv->next = redirlist;
    131 		redirlist = sv;
    132 	}
    133 	for (n = redir ; n ; n = n->nfile.next) {
    134 		fd = n->nfile.fd;
    135 		try = 0;
    136 		if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
    137 		    n->ndup.dupfd == fd)
    138 			continue; /* redirect from/to same file descriptor */
    139 
    140 		if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
    141 			INTOFF;
    142 again:
    143 			if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
    144 				switch (errno) {
    145 				case EBADF:
    146 					if (!try) {
    147 						openredirect(n, memory);
    148 						try++;
    149 						goto again;
    150 					}
    151 					/* FALLTHROUGH*/
    152 				default:
    153 					INTON;
    154 					error("%d: %s", fd, strerror(errno));
    155 					/* NOTREACHED */
    156 				}
    157 			}
    158 			if (!try) {
    159 				sv->renamed[fd] = i;
    160 				close(fd);
    161 			}
    162 			INTON;
    163 		} else {
    164 			close(fd);
    165 		}
    166                 if (fd == 0)
    167                         fd0_redirected++;
    168 		if (!try)
    169 			openredirect(n, memory);
    170 	}
    171 	if (memory[1])
    172 		out1 = &memout;
    173 	if (memory[2])
    174 		out2 = &memout;
    175 }
    176 
    177 
    178 STATIC void
    179 openredirect(redir, memory)
    180 	union node *redir;
    181 	char memory[10];
    182 	{
    183 	int fd = redir->nfile.fd;
    184 	char *fname;
    185 	int f;
    186 	int flags = O_WRONLY|O_CREAT|O_TRUNC;
    187 
    188 	/*
    189 	 * We suppress interrupts so that we won't leave open file
    190 	 * descriptors around.  This may not be such a good idea because
    191 	 * an open of a device or a fifo can block indefinitely.
    192 	 */
    193 	INTOFF;
    194 	memory[fd] = 0;
    195 	switch (redir->nfile.type) {
    196 	case NFROM:
    197 		fname = redir->nfile.expfname;
    198 		if ((f = open(fname, O_RDONLY)) < 0)
    199 			goto eopen;
    200 		break;
    201 	case NFROMTO:
    202 		fname = redir->nfile.expfname;
    203 		if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
    204 			goto ecreate;
    205 		break;
    206 	case NTO:
    207 		if (Cflag)
    208 			flags |= O_EXCL;
    209 		/* FALLTHROUGH */
    210 	case NCLOBBER:
    211 		fname = redir->nfile.expfname;
    212 		if ((f = open(fname, flags, 0666)) < 0)
    213 			goto ecreate;
    214 		break;
    215 	case NAPPEND:
    216 		fname = redir->nfile.expfname;
    217 		if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
    218 			goto ecreate;
    219 		break;
    220 	case NTOFD:
    221 	case NFROMFD:
    222 		if (redir->ndup.dupfd >= 0) {	/* if not ">&-" */
    223 			if (memory[redir->ndup.dupfd])
    224 				memory[fd] = 1;
    225 			else
    226 				copyfd(redir->ndup.dupfd, fd);
    227 		}
    228 		INTON;
    229 		return;
    230 	case NHERE:
    231 	case NXHERE:
    232 		f = openhere(redir);
    233 		break;
    234 	default:
    235 		abort();
    236 	}
    237 
    238 	if (f != fd) {
    239 		copyfd(f, fd);
    240 		close(f);
    241 	}
    242 	INTON;
    243 	return;
    244 ecreate:
    245 	error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
    246 eopen:
    247 	error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
    248 }
    249 
    250 
    251 /*
    252  * Handle here documents.  Normally we fork off a process to write the
    253  * data to a pipe.  If the document is short, we can stuff the data in
    254  * the pipe without forking.
    255  */
    256 
    257 STATIC int
    258 openhere(redir)
    259 	union node *redir;
    260 	{
    261 	int pip[2];
    262 	int len = 0;
    263 
    264 	if (pipe(pip) < 0)
    265 		error("Pipe call failed");
    266 	if (redir->type == NHERE) {
    267 		len = strlen(redir->nhere.doc->narg.text);
    268 		if (len <= PIPESIZE) {
    269 			xwrite(pip[1], redir->nhere.doc->narg.text, len);
    270 			goto out;
    271 		}
    272 	}
    273 	if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
    274 		close(pip[0]);
    275 		signal(SIGINT, SIG_IGN);
    276 		signal(SIGQUIT, SIG_IGN);
    277 		signal(SIGHUP, SIG_IGN);
    278 #ifdef SIGTSTP
    279 		signal(SIGTSTP, SIG_IGN);
    280 #endif
    281 		signal(SIGPIPE, SIG_DFL);
    282 		if (redir->type == NHERE)
    283 			xwrite(pip[1], redir->nhere.doc->narg.text, len);
    284 		else
    285 			expandhere(redir->nhere.doc, pip[1]);
    286 		_exit(0);
    287 	}
    288 out:
    289 	close(pip[1]);
    290 	return pip[0];
    291 }
    292 
    293 
    294 
    295 /*
    296  * Undo the effects of the last redirection.
    297  */
    298 
    299 void
    300 popredir() {
    301 	struct redirtab *rp = redirlist;
    302 	int i;
    303 
    304 	for (i = 0 ; i < 10 ; i++) {
    305 		if (rp->renamed[i] != EMPTY) {
    306                         if (i == 0)
    307                                 fd0_redirected--;
    308 			close(i);
    309 			if (rp->renamed[i] >= 0) {
    310 				copyfd(rp->renamed[i], i);
    311 				close(rp->renamed[i]);
    312 			}
    313 		}
    314 	}
    315 	INTOFF;
    316 	redirlist = rp->next;
    317 	ckfree(rp);
    318 	INTON;
    319 }
    320 
    321 /*
    322  * Undo all redirections.  Called on error or interrupt.
    323  */
    324 
    325 #ifdef mkinit
    326 
    327 INCLUDE "redir.h"
    328 
    329 RESET {
    330 	while (redirlist)
    331 		popredir();
    332 }
    333 
    334 SHELLPROC {
    335 	clearredir(0);
    336 }
    337 
    338 #endif
    339 
    340 /* Return true if fd 0 has already been redirected at least once.  */
    341 int
    342 fd0_redirected_p () {
    343         return fd0_redirected != 0;
    344 }
    345 
    346 /*
    347  * Discard all saved file descriptors.
    348  */
    349 
    350 void
    351 clearredir(vforked)
    352 	int vforked;
    353 {
    354 	struct redirtab *rp;
    355 	int i;
    356 
    357 	for (rp = redirlist ; rp ; rp = rp->next) {
    358 		for (i = 0 ; i < 10 ; i++) {
    359 			if (rp->renamed[i] >= 0) {
    360 				close(rp->renamed[i]);
    361 			}
    362 			if (!vforked)
    363 				rp->renamed[i] = EMPTY;
    364 		}
    365 	}
    366 }
    367 
    368 
    369 
    370 /*
    371  * Copy a file descriptor to be >= to.  Returns -1
    372  * if the source file descriptor is closed, EMPTY if there are no unused
    373  * file descriptors left.
    374  */
    375 
    376 int
    377 copyfd(from, to)
    378 	int from;
    379 	int to;
    380 {
    381 	int newfd;
    382 
    383 	newfd = fcntl(from, F_DUPFD, to);
    384 	if (newfd < 0) {
    385 		if (errno == EMFILE)
    386 			return EMPTY;
    387 		else
    388 			error("%d: %s", from, strerror(errno));
    389 	}
    390 	return newfd;
    391 }
    392