Home | History | Annotate | Line # | Download | only in sh
redir.c revision 1.22
      1 /*	$NetBSD: redir.c,v 1.22 2000/05/22 10:18:47 elric 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.22 2000/05/22 10:18:47 elric 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 "expand.h"
     65 #include "redir.h"
     66 #include "output.h"
     67 #include "memalloc.h"
     68 #include "error.h"
     69 
     70 
     71 #define EMPTY -2		/* marks an unused slot in redirtab */
     72 #ifndef PIPE_BUF
     73 # define PIPESIZE 4096		/* amount of buffering in a pipe */
     74 #else
     75 # define PIPESIZE PIPE_BUF
     76 #endif
     77 
     78 
     79 MKINIT
     80 struct redirtab {
     81 	struct redirtab *next;
     82 	short renamed[10];
     83 };
     84 
     85 
     86 MKINIT struct redirtab *redirlist;
     87 
     88 /*
     89  * We keep track of whether or not fd0 has been redirected.  This is for
     90  * background commands, where we want to redirect fd0 to /dev/null only
     91  * if it hasn't already been redirected.
     92 */
     93 int fd0_redirected = 0;
     94 
     95 STATIC void openredirect __P((union node *, char[10 ]));
     96 STATIC int openhere __P((union node *));
     97 
     98 
     99 /*
    100  * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
    101  * old file descriptors are stashed away so that the redirection can be
    102  * undone by calling popredir.  If the REDIR_BACKQ flag is set, then the
    103  * standard output, and the standard error if it becomes a duplicate of
    104  * stdout, is saved in memory.
    105  */
    106 
    107 void
    108 redirect(redir, flags)
    109 	union node *redir;
    110 	int flags;
    111 	{
    112 	union node *n;
    113 	struct redirtab *sv = NULL;
    114 	int i;
    115 	int fd;
    116 	int try;
    117 	char memory[10];	/* file descriptors to write to memory */
    118 
    119 	for (i = 10 ; --i >= 0 ; )
    120 		memory[i] = 0;
    121 	memory[1] = flags & REDIR_BACKQ;
    122 	if (flags & REDIR_PUSH) {
    123 		sv = ckmalloc(sizeof (struct redirtab));
    124 		for (i = 0 ; i < 10 ; i++)
    125 			sv->renamed[i] = EMPTY;
    126 		sv->next = redirlist;
    127 		redirlist = sv;
    128 	}
    129 	for (n = redir ; n ; n = n->nfile.next) {
    130 		fd = n->nfile.fd;
    131 		try = 0;
    132 		if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
    133 		    n->ndup.dupfd == fd)
    134 			continue; /* redirect from/to same file descriptor */
    135 
    136 		if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
    137 			INTOFF;
    138 again:
    139 			if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
    140 				switch (errno) {
    141 				case EBADF:
    142 					if (!try) {
    143 						openredirect(n, memory);
    144 						try++;
    145 						goto again;
    146 					}
    147 					/* FALLTHROUGH*/
    148 				default:
    149 					INTON;
    150 					error("%d: %s", fd, strerror(errno));
    151 					/* NOTREACHED */
    152 				}
    153 			}
    154 			if (!try) {
    155 				sv->renamed[fd] = i;
    156 				close(fd);
    157 			}
    158 			INTON;
    159 		} else {
    160 			close(fd);
    161 		}
    162                 if (fd == 0)
    163                         fd0_redirected++;
    164 		if (!try)
    165 			openredirect(n, memory);
    166 	}
    167 	if (memory[1])
    168 		out1 = &memout;
    169 	if (memory[2])
    170 		out2 = &memout;
    171 }
    172 
    173 
    174 STATIC void
    175 openredirect(redir, memory)
    176 	union node *redir;
    177 	char memory[10];
    178 	{
    179 	int fd = redir->nfile.fd;
    180 	char *fname;
    181 	int f;
    182 
    183 	/*
    184 	 * We suppress interrupts so that we won't leave open file
    185 	 * descriptors around.  This may not be such a good idea because
    186 	 * an open of a device or a fifo can block indefinitely.
    187 	 */
    188 	INTOFF;
    189 	memory[fd] = 0;
    190 	switch (redir->nfile.type) {
    191 	case NFROM:
    192 		fname = redir->nfile.expfname;
    193 		if ((f = open(fname, O_RDONLY)) < 0)
    194 			goto eopen;
    195 		break;
    196 	case NFROMTO:
    197 		fname = redir->nfile.expfname;
    198 		if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
    199 			goto ecreate;
    200 		break;
    201 	case NTO:
    202 		fname = redir->nfile.expfname;
    203 #ifdef O_CREAT
    204 		if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
    205 			goto ecreate;
    206 #else
    207 		if ((f = creat(fname, 0666)) < 0)
    208 			goto ecreate;
    209 #endif
    210 		break;
    211 	case NAPPEND:
    212 		fname = redir->nfile.expfname;
    213 #ifdef O_APPEND
    214 		if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
    215 			goto ecreate;
    216 #else
    217 		if ((f = open(fname, O_WRONLY)) < 0
    218 		 && (f = creat(fname, 0666)) < 0)
    219 			goto ecreate;
    220 		lseek(f, (off_t)0, 2);
    221 #endif
    222 		break;
    223 	case NTOFD:
    224 	case NFROMFD:
    225 		if (redir->ndup.dupfd >= 0) {	/* if not ">&-" */
    226 			if (memory[redir->ndup.dupfd])
    227 				memory[fd] = 1;
    228 			else
    229 				copyfd(redir->ndup.dupfd, fd);
    230 		}
    231 		INTON;
    232 		return;
    233 	case NHERE:
    234 	case NXHERE:
    235 		f = openhere(redir);
    236 		break;
    237 	default:
    238 		abort();
    239 	}
    240 
    241 	if (f != fd) {
    242 		copyfd(f, fd);
    243 		close(f);
    244 	}
    245 	INTON;
    246 	return;
    247 ecreate:
    248 	error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
    249 eopen:
    250 	error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
    251 }
    252 
    253 
    254 /*
    255  * Handle here documents.  Normally we fork off a process to write the
    256  * data to a pipe.  If the document is short, we can stuff the data in
    257  * the pipe without forking.
    258  */
    259 
    260 STATIC int
    261 openhere(redir)
    262 	union node *redir;
    263 	{
    264 	int pip[2];
    265 	int len = 0;
    266 
    267 	if (pipe(pip) < 0)
    268 		error("Pipe call failed");
    269 	if (redir->type == NHERE) {
    270 		len = strlen(redir->nhere.doc->narg.text);
    271 		if (len <= PIPESIZE) {
    272 			xwrite(pip[1], redir->nhere.doc->narg.text, len);
    273 			goto out;
    274 		}
    275 	}
    276 	if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
    277 		close(pip[0]);
    278 		signal(SIGINT, SIG_IGN);
    279 		signal(SIGQUIT, SIG_IGN);
    280 		signal(SIGHUP, SIG_IGN);
    281 #ifdef SIGTSTP
    282 		signal(SIGTSTP, SIG_IGN);
    283 #endif
    284 		signal(SIGPIPE, SIG_DFL);
    285 		if (redir->type == NHERE)
    286 			xwrite(pip[1], redir->nhere.doc->narg.text, len);
    287 		else
    288 			expandhere(redir->nhere.doc, pip[1]);
    289 		_exit(0);
    290 	}
    291 out:
    292 	close(pip[1]);
    293 	return pip[0];
    294 }
    295 
    296 
    297 
    298 /*
    299  * Undo the effects of the last redirection.
    300  */
    301 
    302 void
    303 popredir() {
    304 	struct redirtab *rp = redirlist;
    305 	int i;
    306 
    307 	for (i = 0 ; i < 10 ; i++) {
    308 		if (rp->renamed[i] != EMPTY) {
    309                         if (i == 0)
    310                                 fd0_redirected--;
    311 			close(i);
    312 			if (rp->renamed[i] >= 0) {
    313 				copyfd(rp->renamed[i], i);
    314 				close(rp->renamed[i]);
    315 			}
    316 		}
    317 	}
    318 	INTOFF;
    319 	redirlist = rp->next;
    320 	ckfree(rp);
    321 	INTON;
    322 }
    323 
    324 /*
    325  * Undo all redirections.  Called on error or interrupt.
    326  */
    327 
    328 #ifdef mkinit
    329 
    330 INCLUDE "redir.h"
    331 
    332 RESET {
    333 	while (redirlist)
    334 		popredir();
    335 }
    336 
    337 SHELLPROC {
    338 	clearredir();
    339 }
    340 
    341 #endif
    342 
    343 /* Return true if fd 0 has already been redirected at least once.  */
    344 int
    345 fd0_redirected_p () {
    346         return fd0_redirected != 0;
    347 }
    348 
    349 /*
    350  * Discard all saved file descriptors.
    351  */
    352 
    353 void
    354 clearredir() {
    355 	struct redirtab *rp;
    356 	int i;
    357 
    358 	for (rp = redirlist ; rp ; rp = rp->next) {
    359 		for (i = 0 ; i < 10 ; i++) {
    360 			if (rp->renamed[i] >= 0) {
    361 				close(rp->renamed[i]);
    362 			}
    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