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