Home | History | Annotate | Line # | Download | only in sh
redir.c revision 1.21
      1 /*	$NetBSD: redir.c,v 1.21 2000/05/13 20:50:15 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.21 2000/05/13 20:50:15 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 		/* We don't have to worry about REDIR_VFORK here, as
    124 		 * flags & REDIR_PUSH is never true if REDIR_VFORK is set.
    125 		 */
    126 		sv = ckmalloc(sizeof (struct redirtab));
    127 		for (i = 0 ; i < 10 ; i++)
    128 			sv->renamed[i] = EMPTY;
    129 		sv->next = redirlist;
    130 		redirlist = sv;
    131 	}
    132 	for (n = redir ; n ; n = n->nfile.next) {
    133 		fd = n->nfile.fd;
    134 		try = 0;
    135 		if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
    136 		    n->ndup.dupfd == fd)
    137 			continue; /* redirect from/to same file descriptor */
    138 
    139 		if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
    140 			INTOFF;
    141 again:
    142 			if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
    143 				switch (errno) {
    144 				case EBADF:
    145 					if (!try) {
    146 						openredirect(n, memory);
    147 						try++;
    148 						goto again;
    149 					}
    150 					/* FALLTHROUGH*/
    151 				default:
    152 					INTON;
    153 					error("%d: %s", fd, strerror(errno));
    154 					/* NOTREACHED */
    155 				}
    156 			}
    157 			if (!try) {
    158 				sv->renamed[fd] = i;
    159 				close(fd);
    160 			}
    161 			INTON;
    162 		} else {
    163 			close(fd);
    164 		}
    165                 if (fd == 0)
    166                         fd0_redirected++;
    167 		if (!try)
    168 			openredirect(n, memory);
    169 	}
    170 	if (memory[1])
    171 		out1 = &memout;
    172 	if (memory[2])
    173 		out2 = &memout;
    174 }
    175 
    176 
    177 STATIC void
    178 openredirect(redir, memory)
    179 	union node *redir;
    180 	char memory[10];
    181 	{
    182 	int fd = redir->nfile.fd;
    183 	char *fname;
    184 	int f;
    185 
    186 	/*
    187 	 * We suppress interrupts so that we won't leave open file
    188 	 * descriptors around.  This may not be such a good idea because
    189 	 * an open of a device or a fifo can block indefinitely.
    190 	 */
    191 	INTOFF;
    192 	memory[fd] = 0;
    193 	switch (redir->nfile.type) {
    194 	case NFROM:
    195 		fname = redir->nfile.expfname;
    196 		if ((f = open(fname, O_RDONLY)) < 0)
    197 			goto eopen;
    198 		break;
    199 	case NFROMTO:
    200 		fname = redir->nfile.expfname;
    201 		if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
    202 			goto ecreate;
    203 		break;
    204 	case NTO:
    205 		fname = redir->nfile.expfname;
    206 #ifdef O_CREAT
    207 		if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
    208 			goto ecreate;
    209 #else
    210 		if ((f = creat(fname, 0666)) < 0)
    211 			goto ecreate;
    212 #endif
    213 		break;
    214 	case NAPPEND:
    215 		fname = redir->nfile.expfname;
    216 #ifdef O_APPEND
    217 		if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
    218 			goto ecreate;
    219 #else
    220 		if ((f = open(fname, O_WRONLY)) < 0
    221 		 && (f = creat(fname, 0666)) < 0)
    222 			goto ecreate;
    223 		lseek(f, (off_t)0, 2);
    224 #endif
    225 		break;
    226 	case NTOFD:
    227 	case NFROMFD:
    228 		if (redir->ndup.dupfd >= 0) {	/* if not ">&-" */
    229 			if (memory[redir->ndup.dupfd])
    230 				memory[fd] = 1;
    231 			else
    232 				copyfd(redir->ndup.dupfd, fd);
    233 		}
    234 		INTON;
    235 		return;
    236 	case NHERE:
    237 	case NXHERE:
    238 		f = openhere(redir);
    239 		break;
    240 	default:
    241 		abort();
    242 	}
    243 
    244 	if (f != fd) {
    245 		copyfd(f, fd);
    246 		close(f);
    247 	}
    248 	INTON;
    249 	return;
    250 ecreate:
    251 	error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
    252 eopen:
    253 	error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
    254 }
    255 
    256 
    257 /*
    258  * Handle here documents.  Normally we fork off a process to write the
    259  * data to a pipe.  If the document is short, we can stuff the data in
    260  * the pipe without forking.
    261  */
    262 
    263 STATIC int
    264 openhere(redir)
    265 	union node *redir;
    266 	{
    267 	int pip[2];
    268 	int len = 0;
    269 
    270 	if (pipe(pip) < 0)
    271 		error("Pipe call failed");
    272 	if (redir->type == NHERE) {
    273 		len = strlen(redir->nhere.doc->narg.text);
    274 		if (len <= PIPESIZE) {
    275 			xwrite(pip[1], redir->nhere.doc->narg.text, len);
    276 			goto out;
    277 		}
    278 	}
    279 	if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
    280 		close(pip[0]);
    281 		signal(SIGINT, SIG_IGN);
    282 		signal(SIGQUIT, SIG_IGN);
    283 		signal(SIGHUP, SIG_IGN);
    284 #ifdef SIGTSTP
    285 		signal(SIGTSTP, SIG_IGN);
    286 #endif
    287 		signal(SIGPIPE, SIG_DFL);
    288 		if (redir->type == NHERE)
    289 			xwrite(pip[1], redir->nhere.doc->narg.text, len);
    290 		else
    291 			expandhere(redir->nhere.doc, pip[1]);
    292 		_exit(0);
    293 	}
    294 out:
    295 	close(pip[1]);
    296 	return pip[0];
    297 }
    298 
    299 
    300 
    301 /*
    302  * Undo the effects of the last redirection.
    303  */
    304 
    305 void
    306 popredir() {
    307 	struct redirtab *rp = redirlist;
    308 	int i;
    309 
    310 	for (i = 0 ; i < 10 ; i++) {
    311 		if (rp->renamed[i] != EMPTY) {
    312                         if (i == 0)
    313                                 fd0_redirected--;
    314 			close(i);
    315 			if (rp->renamed[i] >= 0) {
    316 				copyfd(rp->renamed[i], i);
    317 				close(rp->renamed[i]);
    318 			}
    319 		}
    320 	}
    321 	INTOFF;
    322 	redirlist = rp->next;
    323 	ckfree(rp);
    324 	INTON;
    325 }
    326 
    327 /*
    328  * Undo all redirections.  Called on error or interrupt.
    329  */
    330 
    331 #ifdef mkinit
    332 
    333 INCLUDE "redir.h"
    334 
    335 RESET {
    336 	while (redirlist)
    337 		popredir();
    338 }
    339 
    340 SHELLPROC {
    341 	clearredir(0);
    342 }
    343 
    344 #endif
    345 
    346 /* Return true if fd 0 has already been redirected at least once.  */
    347 int
    348 fd0_redirected_p () {
    349         return fd0_redirected != 0;
    350 }
    351 
    352 /*
    353  * Discard all saved file descriptors.
    354  */
    355 
    356 void
    357 clearredir(vforked)
    358 	int vforked;
    359 {
    360 	struct redirtab *rp;
    361 	int i;
    362 
    363 	for (rp = redirlist ; rp ; rp = rp->next) {
    364 		for (i = 0 ; i < 10 ; i++) {
    365 			if (rp->renamed[i] >= 0) {
    366 				close(rp->renamed[i]);
    367 			}
    368 			if (!vforked)
    369 				rp->renamed[i] = EMPTY;
    370 		}
    371 	}
    372 }
    373 
    374 
    375 
    376 /*
    377  * Copy a file descriptor to be >= to.  Returns -1
    378  * if the source file descriptor is closed, EMPTY if there are no unused
    379  * file descriptors left.
    380  */
    381 
    382 int
    383 copyfd(from, to)
    384 	int from;
    385 	int to;
    386 {
    387 	int newfd;
    388 
    389 	newfd = fcntl(from, F_DUPFD, to);
    390 	if (newfd < 0) {
    391 		if (errno == EMFILE)
    392 			return EMPTY;
    393 		else
    394 			error("%d: %s", from, strerror(errno));
    395 	}
    396 	return newfd;
    397 }
    398