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