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