Home | History | Annotate | Line # | Download | only in sh
redir.c revision 1.70
      1 /*	$NetBSD: redir.c,v 1.70 2021/11/10 15:26:34 kre 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.70 2021/11/10 15:26:34 kre Exp $");
     41 #endif
     42 #endif /* not lint */
     43 
     44 #include <sys/types.h>
     45 #include <sys/param.h>	/* PIPE_BUF */
     46 #include <sys/stat.h>
     47 #include <signal.h>
     48 #include <string.h>
     49 #include <fcntl.h>
     50 #include <errno.h>
     51 #include <unistd.h>
     52 #include <stdlib.h>
     53 
     54 /*
     55  * Code for dealing with input/output redirection.
     56  */
     57 
     58 #include "main.h"
     59 #include "builtins.h"
     60 #include "shell.h"
     61 #include "nodes.h"
     62 #include "jobs.h"
     63 #include "options.h"
     64 #include "expand.h"
     65 #include "redir.h"
     66 #include "output.h"
     67 #include "memalloc.h"
     68 #include "mystring.h"
     69 #include "error.h"
     70 #include "show.h"
     71 
     72 
     73 #define EMPTY -2		/* marks an unused slot in redirtab */
     74 #define CLOSED -1		/* fd was not open before redir */
     75 #ifndef PIPE_BUF
     76 # define PIPESIZE 4096		/* amount of buffering in a pipe */
     77 #else
     78 # define PIPESIZE PIPE_BUF
     79 #endif
     80 
     81 #ifndef FD_CLOEXEC
     82 # define FD_CLOEXEC	1	/* well known from before there was a name */
     83 #endif
     84 
     85 #ifndef F_DUPFD_CLOEXEC
     86 #define F_DUPFD_CLOEXEC	F_DUPFD
     87 #define CLOEXEC(fd)	(fcntl((fd), F_SETFD, fcntl((fd),F_GETFD) | FD_CLOEXEC))
     88 #else
     89 #define CLOEXEC(fd)
     90 #endif
     91 
     92 
     93 MKINIT
     94 struct renamelist {
     95 	struct renamelist *next;
     96 	int orig;
     97 	int into;
     98 };
     99 
    100 MKINIT
    101 struct redirtab {
    102 	struct redirtab *next;
    103 	struct renamelist *renamed;
    104 };
    105 
    106 
    107 MKINIT struct redirtab *redirlist;
    108 
    109 /*
    110  * We keep track of whether or not fd0 has been redirected.  This is for
    111  * background commands, where we want to redirect fd0 to /dev/null only
    112  * if it hasn't already been redirected.
    113  */
    114 STATIC int fd0_redirected = 0;
    115 
    116 /*
    117  * And also where to put internal use fds that should be out of the
    118  * way of user defined fds (normally)
    119  */
    120 STATIC int big_sh_fd = 0;
    121 
    122 STATIC const struct renamelist *is_renamed(const struct renamelist *, int);
    123 STATIC void fd_rename(struct redirtab *, int, int);
    124 STATIC int * saved_redirected_fd(int);
    125 STATIC void free_rl(struct redirtab *, int);
    126 STATIC void openredirect(union node *, char[10], int);
    127 STATIC int openhere(const union node *);
    128 STATIC int copyfd(int, int, int);
    129 STATIC void find_big_fd(void);
    130 
    131 
    132 struct shell_fds {		/* keep track of internal shell fds */
    133 	struct shell_fds *nxt;
    134 	void (*cb)(int, int);
    135 	int fd;
    136 };
    137 
    138 STATIC struct shell_fds *sh_fd_list;
    139 
    140 STATIC int pick_new_fd(int);
    141 STATIC void renumber_sh_fd(struct shell_fds *);
    142 STATIC struct shell_fds *sh_fd(int);
    143 
    144 STATIC const struct renamelist *
    145 is_renamed(const struct renamelist *rl, int fd)
    146 {
    147 	while (rl != NULL) {
    148 		if (rl->orig == fd)
    149 			return rl;
    150 		rl = rl->next;
    151 	}
    152 	return NULL;
    153 }
    154 
    155 STATIC int *
    156 saved_redirected_fd(int fd)
    157 {
    158 	struct redirtab *rt;
    159 	struct renamelist *rl;
    160 
    161 	for (rt = redirlist; rt != NULL; rt = rt->next) {
    162 		for (rl =  rt->renamed; rl != NULL; rl = rl->next) {
    163 			if (rl->into == fd)
    164 				return &rl->into;
    165 		}
    166 	}
    167 	return NULL;
    168 }
    169 
    170 STATIC void
    171 free_rl(struct redirtab *rt, int reset)
    172 {
    173 	struct renamelist *rl, *rn = rt->renamed;
    174 
    175 	while ((rl = rn) != NULL) {
    176 		rn = rl->next;
    177 		if (rl->orig == 0)
    178 			fd0_redirected--;
    179 		VTRACE(DBG_REDIR, ("popredir %d%s: %s",
    180 		    rl->orig, rl->orig==0 ? " (STDIN)" : "",
    181 		    reset ? "" : "no reset\n"));
    182 		if (reset) {
    183 			if (rl->into < 0) {
    184 				VTRACE(DBG_REDIR, ("closed\n"));
    185 				close(rl->orig);
    186 			} else {
    187 				VTRACE(DBG_REDIR, ("from %d\n", rl->into));
    188 				movefd(rl->into, rl->orig);
    189 			}
    190 		}
    191 		ckfree(rl);
    192 	}
    193 	rt->renamed = NULL;
    194 }
    195 
    196 STATIC void
    197 fd_rename(struct redirtab *rt, int from, int to)
    198 {
    199 	/* XXX someday keep a short list (8..10) of freed renamelists XXX */
    200 	struct renamelist *rl = ckmalloc(sizeof(struct renamelist));
    201 
    202 	rl->next = rt->renamed;
    203 	rt->renamed = rl;
    204 
    205 	rl->orig = from;
    206 	rl->into = to;
    207 }
    208 
    209 /*
    210  * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
    211  * old file descriptors are stashed away so that the redirection can be
    212  * undone by calling popredir.  If the REDIR_BACKQ flag is set, then the
    213  * standard output, and the standard error if it becomes a duplicate of
    214  * stdout, is saved in memory.
    215  */
    216 
    217 void
    218 redirect(union node *redir, int flags)
    219 {
    220 	union node *n;
    221 	struct redirtab *sv = NULL;
    222 	int i;
    223 	int fd;
    224 	char memory[10];	/* file descriptors to write to memory */
    225 
    226 	CTRACE(DBG_REDIR, ("redirect(F=0x%x):%s\n", flags, redir?"":" NONE"));
    227 	for (i = 10 ; --i >= 0 ; )
    228 		memory[i] = 0;
    229 	memory[1] = flags & REDIR_BACKQ;
    230 	if (flags & REDIR_PUSH) {
    231 		/*
    232 		 * We don't have to worry about REDIR_VFORK here, as
    233 		 * flags & REDIR_PUSH is never true if REDIR_VFORK is set.
    234 		 */
    235 		sv = ckmalloc(sizeof (struct redirtab));
    236 		sv->renamed = NULL;
    237 		sv->next = redirlist;
    238 		redirlist = sv;
    239 	}
    240 	for (n = redir ; n ; n = n->nfile.next) {
    241 		int *renamed;
    242 
    243 		fd = n->nfile.fd;
    244 		VTRACE(DBG_REDIR, ("redir %d (max=%d limit=%ld) ",
    245 		    fd, max_user_fd, user_fd_limit));
    246 		if (fd < user_fd_limit && fd > max_user_fd)
    247 			max_user_fd = fd;
    248 		if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
    249 		    n->ndup.dupfd == fd) {
    250 			VTRACE(DBG_REDIR, ("!cloexec\n"));
    251 			if (sh_fd(fd) != NULL ||
    252 			    saved_redirected_fd(fd) != NULL)
    253 				error("fd %d: %s", fd, strerror(EBADF));
    254 			/* redirect from/to same file descriptor */
    255 			/* make sure it stays open */
    256 			if (fcntl(fd, F_SETFD, 0) < 0)
    257 				error("fd %d: %s", fd, strerror(errno));
    258 			continue;
    259 		}
    260 		if ((renamed = saved_redirected_fd(fd)) != NULL) {
    261 			int to = pick_new_fd(fd);
    262 
    263 			VTRACE(DBG_REDIR,
    264 			    ("redirect: moved holding fd %d to %d\n", fd, to));
    265 			*renamed = to;
    266 			if (to != fd)	/* always... */
    267 				(void)close(fd);
    268 		}
    269 		renumber_sh_fd(sh_fd(fd));
    270 
    271 		if ((flags & REDIR_PUSH) && !is_renamed(sv->renamed, fd)) {
    272 			int bigfd;
    273 
    274 			INTOFF;
    275 			if (big_sh_fd < 10)
    276 				find_big_fd();
    277 			if ((bigfd = big_sh_fd) < max_user_fd)
    278 				bigfd = max_user_fd;
    279 			if ((i = fcntl(fd, F_DUPFD, bigfd + 1)) == -1) {
    280 				switch (errno) {
    281 				case EBADF:
    282 					i = CLOSED;
    283 					break;
    284 				case EMFILE:
    285 				case EINVAL:
    286 					find_big_fd();
    287 					i = fcntl(fd, F_DUPFD, big_sh_fd);
    288 					if (i >= 0)
    289 						break;
    290 					if (errno == EMFILE || errno == EINVAL)
    291 						i = fcntl(fd, F_DUPFD, 3);
    292 					if (i >= 0)
    293 						break;
    294 					/* FALLTHRU */
    295 				default:
    296 					error("%d: %s", fd, strerror(errno));
    297 					/* NOTREACHED */
    298 				}
    299 			}
    300 			if (i >= 0)
    301 				(void)fcntl(i, F_SETFD, FD_CLOEXEC);
    302 			fd_rename(sv, fd, i);
    303 			VTRACE(DBG_REDIR, ("fd %d saved as %d ", fd, i));
    304 			INTON;
    305 		}
    306 		VTRACE(DBG_REDIR, ("%s\n", fd == 0 ? "STDIN" : ""));
    307 		if (fd == 0)
    308 			fd0_redirected++;
    309 		openredirect(n, memory, flags);
    310 	}
    311 	if (memory[1])
    312 		out1 = &memout;
    313 	if (memory[2])
    314 		out2 = &memout;
    315 }
    316 
    317 
    318 STATIC void
    319 openredirect(union node *redir, char memory[10], int flags)
    320 {
    321 	struct stat sb;
    322 	int fd = redir->nfile.fd;
    323 	char *fname;
    324 	int f;
    325 	int eflags, cloexec;
    326 
    327 	/*
    328 	 * We suppress interrupts so that we won't leave open file
    329 	 * descriptors around.  This may not be such a good idea because
    330 	 * an open of a device or a fifo can block indefinitely.
    331 	 */
    332 	INTOFF;
    333 	if (fd < 10)
    334 		memory[fd] = 0;
    335 	switch (redir->nfile.type) {
    336 	case NFROM:
    337 		fname = redir->nfile.expfname;
    338 		if (flags & REDIR_VFORK)
    339 			eflags = O_NONBLOCK;
    340 		else
    341 			eflags = 0;
    342 		if ((f = open(fname, O_RDONLY|eflags)) < 0)
    343 			goto eopen;
    344 		VTRACE(DBG_REDIR, ("openredirect(< '%s') -> %d [%#x]",
    345 		    fname, f, eflags));
    346 		if (eflags)
    347 			(void)fcntl(f, F_SETFL, fcntl(f, F_GETFL, 0) & ~eflags);
    348 		break;
    349 	case NFROMTO:
    350 		fname = redir->nfile.expfname;
    351 		if ((f = open(fname, O_RDWR|O_CREAT, 0666)) < 0)
    352 			goto ecreate;
    353 		VTRACE(DBG_REDIR, ("openredirect(<> '%s') -> %d", fname, f));
    354 		break;
    355 	case NTO:
    356 		if (Cflag) {
    357 			fname = redir->nfile.expfname;
    358 			if ((f = open(fname, O_WRONLY)) == -1) {
    359 				if ((f = open(fname, O_WRONLY|O_CREAT|O_EXCL,
    360 				    0666)) < 0)
    361 					goto ecreate;
    362 			} else if (fstat(f, &sb) == -1) {
    363 				int serrno = errno;
    364 				close(f);
    365 				errno = serrno;
    366 				goto ecreate;
    367 			} else if (S_ISREG(sb.st_mode)) {
    368 				close(f);
    369 				errno = EEXIST;
    370 				goto ecreate;
    371 			}
    372 			VTRACE(DBG_REDIR, ("openredirect(>| '%s') -> %d",
    373 			    fname, f));
    374 			break;
    375 		}
    376 		/* FALLTHROUGH */
    377 	case NCLOBBER:
    378 		fname = redir->nfile.expfname;
    379 		if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
    380 			goto ecreate;
    381 		VTRACE(DBG_REDIR, ("openredirect(> '%s') -> %d", fname, f));
    382 		break;
    383 	case NAPPEND:
    384 		fname = redir->nfile.expfname;
    385 		if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
    386 			goto ecreate;
    387 		VTRACE(DBG_REDIR, ("openredirect(>> '%s') -> %d", fname, f));
    388 		break;
    389 	case NTOFD:
    390 	case NFROMFD:
    391 		if (redir->ndup.dupfd >= 0) {	/* if not ">&-" */
    392 			if (sh_fd(redir->ndup.dupfd) != NULL ||
    393 			    saved_redirected_fd(redir->ndup.dupfd) != NULL)
    394 				error("Redirect (from %d to %d) failed: %s",
    395 				    redir->ndup.dupfd, fd, strerror(EBADF));
    396 			if (fd < 10 && redir->ndup.dupfd < 10 &&
    397 			    memory[redir->ndup.dupfd])
    398 				memory[fd] = 1;
    399 			else if (copyfd(redir->ndup.dupfd, fd,
    400 			    (flags & REDIR_KEEP) == 0) < 0)
    401 				error("Redirect (from %d to %d) failed: %s",
    402 				    redir->ndup.dupfd, fd, strerror(errno));
    403 			VTRACE(DBG_REDIR, ("openredirect: %d%c&%d\n", fd,
    404 			    "<>"[redir->nfile.type==NTOFD], redir->ndup.dupfd));
    405 		} else {
    406 			(void) close(fd);
    407 			VTRACE(DBG_REDIR, ("openredirect: %d%c&-\n", fd,
    408 			    "<>"[redir->nfile.type==NTOFD]));
    409 		}
    410 		INTON;
    411 		return;
    412 	case NHERE:
    413 	case NXHERE:
    414 		VTRACE(DBG_REDIR, ("openredirect: %d<<...", fd));
    415 		f = openhere(redir);
    416 		break;
    417 	default:
    418 		abort();
    419 	}
    420 
    421 	cloexec = fd > 2 && (flags & REDIR_KEEP) == 0 && !posix;
    422 	if (f != fd) {
    423 		VTRACE(DBG_REDIR, (" -> %d", fd));
    424 		if (copyfd(f, fd, cloexec) < 0) {
    425 			int e = errno;
    426 
    427 			VTRACE(DBG_REDIR, (" failed: %s\n", strerror(e)));
    428 			close(f);
    429 			error("redirect reassignment (fd %d) failed: %s", fd,
    430 			    strerror(e));
    431 		}
    432 		close(f);
    433 	} else if (cloexec)
    434 		(void)fcntl(f, F_SETFD, FD_CLOEXEC);
    435 	VTRACE(DBG_REDIR, ("%s\n", cloexec ? " cloexec" : ""));
    436 
    437 	INTON;
    438 	return;
    439  ecreate:
    440 	exerrno = 1;
    441 	error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
    442  eopen:
    443 	exerrno = 1;
    444 	error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
    445 }
    446 
    447 
    448 /*
    449  * Handle here documents.  Normally we fork off a process to write the
    450  * data to a pipe.  If the document is short, we can stuff the data in
    451  * the pipe without forking.
    452  */
    453 
    454 STATIC int
    455 openhere(const union node *redir)
    456 {
    457 	int pip[2];
    458 	int len = 0;
    459 
    460 	if (pipe(pip) < 0)
    461 		error("Pipe call failed");
    462 	if (redir->type == NHERE) {
    463 		len = strlen(redir->nhere.doc->narg.text);
    464 		if (len <= PIPESIZE) {
    465 			xwrite(pip[1], redir->nhere.doc->narg.text, len);
    466 			goto out;
    467 		}
    468 	}
    469 	VTRACE(DBG_REDIR, (" forking [%d,%d]\n", pip[0], pip[1]));
    470 	if (forkshell(NULL, NULL, FORK_NOJOB) == 0) {
    471 		close(pip[0]);
    472 		signal(SIGINT, SIG_IGN);
    473 		signal(SIGQUIT, SIG_IGN);
    474 		signal(SIGHUP, SIG_IGN);
    475 #ifdef SIGTSTP
    476 		signal(SIGTSTP, SIG_IGN);
    477 #endif
    478 		signal(SIGPIPE, SIG_DFL);
    479 		if (redir->type == NHERE)
    480 			xwrite(pip[1], redir->nhere.doc->narg.text, len);
    481 		else
    482 			expandhere(redir->nhere.doc, pip[1]);
    483 		VTRACE(DBG_PROCS|DBG_REDIR, ("wrote here doc.  exiting(0)\n"));
    484 		_exit(0);
    485 	}
    486 	VTRACE(DBG_REDIR, ("openhere (closing %d)", pip[1]));
    487  out:
    488 	close(pip[1]);
    489 	VTRACE(DBG_REDIR, (" (pipe fd=%d)", pip[0]));
    490 	return pip[0];
    491 }
    492 
    493 
    494 
    495 /*
    496  * Undo the effects of the last redirection.
    497  */
    498 
    499 void
    500 popredir(void)
    501 {
    502 	struct redirtab *rp = redirlist;
    503 
    504 	INTOFF;
    505 	free_rl(rp, 1);
    506 	redirlist = rp->next;
    507 	ckfree(rp);
    508 	INTON;
    509 }
    510 
    511 /*
    512  * Undo all redirections.  Called on error or interrupt.
    513  */
    514 
    515 #ifdef mkinit
    516 
    517 INCLUDE "redir.h"
    518 
    519 RESET {
    520 	while (redirlist)
    521 		popredir();
    522 }
    523 
    524 SHELLPROC {
    525 	clearredir(0);
    526 }
    527 
    528 #endif
    529 
    530 /* Return true if fd 0 has already been redirected at least once.  */
    531 int
    532 fd0_redirected_p(void)
    533 {
    534 	return fd0_redirected != 0;
    535 }
    536 
    537 /*
    538  * Discard all saved file descriptors.
    539  */
    540 
    541 void
    542 clearredir(int vforked)
    543 {
    544 	struct redirtab *rp;
    545 	struct renamelist *rl;
    546 
    547 	for (rp = redirlist ; rp ; rp = rp->next) {
    548 		if (!vforked)
    549 			free_rl(rp, 0);
    550 		else for (rl = rp->renamed; rl; rl = rl->next)
    551 			if (rl->into >= 0)
    552 				close(rl->into);
    553 	}
    554 }
    555 
    556 
    557 
    558 /*
    559  * Copy a file descriptor to be == to.
    560  * cloexec indicates if we want close-on-exec or not.
    561  * Returns -1 if any error occurs.
    562  */
    563 
    564 STATIC int
    565 copyfd(int from, int to, int cloexec)
    566 {
    567 	int newfd;
    568 
    569 	if (cloexec && to > 2) {
    570 #ifdef O_CLOEXEC
    571 		newfd = dup3(from, to, O_CLOEXEC);
    572 #else
    573 		newfd = dup2(from, to);
    574 		fcntl(newfd, F_SETFD, fcntl(newfd,F_GETFD) | FD_CLOEXEC);
    575 #endif
    576 	} else
    577 		newfd = dup2(from, to);
    578 
    579 	return newfd;
    580 }
    581 
    582 /*
    583  * rename fd from to be fd to (closing from).
    584  * close-on-exec is never set on 'to' (unless
    585  * from==to and it was set on from) - ie: a no-op
    586  * returns to (or errors() if an error occurs).
    587  *
    588  * This is mostly used for rearranging the
    589  * results from pipe().
    590  */
    591 int
    592 movefd(int from, int to)
    593 {
    594 	if (from == to)
    595 		return to;
    596 
    597 	(void) close(to);
    598 	if (copyfd(from, to, 0) != to) {
    599 		int e = errno;
    600 
    601 		(void) close(from);
    602 		error("Unable to make fd %d: %s", to, strerror(e));
    603 	}
    604 	(void) close(from);
    605 
    606 	return to;
    607 }
    608 
    609 STATIC void
    610 find_big_fd(void)
    611 {
    612 	int i, fd;
    613 	static int last_start = 3; /* aim to keep sh fd's under 20 */
    614 
    615 	if (last_start < 10)
    616 		last_start++;
    617 
    618 	for (i = (1 << last_start); i >= 10; i >>= 1) {
    619 		if ((fd = fcntl(0, F_DUPFD, i - 1)) >= 0) {
    620 			close(fd);
    621 			break;
    622 		}
    623 	}
    624 
    625 	fd = (i / 5) * 4;
    626 	if (fd < 10)
    627 		fd = 10;
    628 
    629 	big_sh_fd = fd;
    630 }
    631 
    632 /*
    633  * If possible, move file descriptor fd out of the way
    634  * of expected user fd values.   Returns the new fd
    635  * (which may be the input fd if things do not go well.)
    636  * Always set close-on-exec on the result, and close
    637  * the input fd unless it is to be our result.
    638  */
    639 int
    640 to_upper_fd(int fd)
    641 {
    642 	int i;
    643 
    644 	VTRACE(DBG_REDIR|DBG_OUTPUT, ("to_upper_fd(%d)", fd));
    645 	if (big_sh_fd < 10 || big_sh_fd >= user_fd_limit)
    646 		find_big_fd();
    647 	do {
    648 		i = fcntl(fd, F_DUPFD_CLOEXEC, big_sh_fd);
    649 		if (i >= 0) {
    650 			if (fd != i)
    651 				close(fd);
    652 			VTRACE(DBG_REDIR|DBG_OUTPUT, ("-> %d\n", i));
    653 			return i;
    654 		}
    655 		if (errno != EMFILE && errno != EINVAL)
    656 			break;
    657 		find_big_fd();
    658 	} while (big_sh_fd > 10);
    659 
    660 	/*
    661 	 * If we wanted to move this fd to some random high number
    662 	 * we certainly do not intend to pass it through exec, even
    663 	 * if the reassignment failed.
    664 	 */
    665 	(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
    666 	VTRACE(DBG_REDIR|DBG_OUTPUT, (" fails ->%d\n", fd));
    667 	return fd;
    668 }
    669 
    670 void
    671 register_sh_fd(int fd, void (*cb)(int, int))
    672 {
    673 	struct shell_fds *fp;
    674 
    675 	fp = ckmalloc(sizeof (struct shell_fds));
    676 	if (fp != NULL) {
    677 		fp->nxt = sh_fd_list;
    678 		sh_fd_list = fp;
    679 
    680 		fp->fd = fd;
    681 		fp->cb = cb;
    682 	}
    683 }
    684 
    685 void
    686 sh_close(int fd)
    687 {
    688 	struct shell_fds **fpp, *fp;
    689 
    690 	fpp = &sh_fd_list;
    691 	while ((fp = *fpp) != NULL) {
    692 		if (fp->fd == fd) {
    693 			*fpp = fp->nxt;
    694 			ckfree(fp);
    695 			break;
    696 		}
    697 		fpp = &fp->nxt;
    698 	}
    699 	(void)close(fd);
    700 }
    701 
    702 STATIC struct shell_fds *
    703 sh_fd(int fd)
    704 {
    705 	struct shell_fds *fp;
    706 
    707 	for (fp = sh_fd_list; fp != NULL; fp = fp->nxt)
    708 		if (fp->fd == fd)
    709 			return fp;
    710 	return NULL;
    711 }
    712 
    713 STATIC int
    714 pick_new_fd(int fd)
    715 {
    716 	int to;
    717 
    718 	to = fcntl(fd, F_DUPFD_CLOEXEC, big_sh_fd);
    719 	if (to == -1 && big_sh_fd >= 22)
    720 		to = fcntl(fd, F_DUPFD_CLOEXEC, big_sh_fd/2);
    721 	if (to == -1)
    722 		to = fcntl(fd, F_DUPFD_CLOEXEC, fd + 1);
    723 	if (to == -1)
    724 		to = fcntl(fd, F_DUPFD_CLOEXEC, 10);
    725 	if (to == -1)
    726 		to = fcntl(fd, F_DUPFD_CLOEXEC, 3);
    727 	if (to == -1)
    728 		error("insufficient file descriptors available");
    729 	CLOEXEC(to);
    730 	return to;
    731 }
    732 
    733 STATIC void
    734 renumber_sh_fd(struct shell_fds *fp)
    735 {
    736 	int to;
    737 
    738 	if (fp == NULL)
    739 		return;
    740 
    741 	/*
    742 	 * if we have had a collision, and the sh fd was a "big" one
    743 	 * try moving the sh fd base to a higher number (if possible)
    744 	 * so future sh fds are less likely to be in the user's sights
    745 	 * (incl this one when moved)
    746 	 */
    747 	if (fp->fd >= big_sh_fd)
    748 		find_big_fd();
    749 
    750 	to = pick_new_fd(fp->fd);
    751 
    752 	if (fp->fd == to)	/* impossible? */
    753 		return;
    754 
    755 	VTRACE(DBG_REDIR, ("renumber_sh_fd: moved shell fd %d to %d\n",
    756 	    fp->fd, to));
    757 
    758 	(*fp->cb)(fp->fd, to);
    759 	(void)close(fp->fd);
    760 	fp->fd = to;
    761 }
    762 
    763 static const struct flgnames {
    764 	const char *name;
    765 	uint16_t minch;
    766 	uint32_t value;
    767 } nv[] = {
    768 #ifdef O_APPEND
    769 	{ "append",	2,	O_APPEND 	},
    770 #else
    771 # define O_APPEND 0
    772 #endif
    773 #ifdef O_ASYNC
    774 	{ "async",	2,	O_ASYNC		},
    775 #else
    776 # define O_ASYNC 0
    777 #endif
    778 #ifdef O_SYNC
    779 	{ "sync",	2,	O_SYNC		},
    780 #else
    781 # define O_SYNC 0
    782 #endif
    783 #ifdef O_NONBLOCK
    784 	{ "nonblock",	3,	O_NONBLOCK	},
    785 #else
    786 # define O_NONBLOCK 0
    787 #endif
    788 #ifdef O_FSYNC
    789 	{ "fsync",	2,	O_FSYNC		},
    790 #else
    791 # define O_FSYNC 0
    792 #endif
    793 #ifdef O_DSYNC
    794 	{ "dsync",	2,	O_DSYNC		},
    795 #else
    796 # define O_DSYNC 0
    797 #endif
    798 #ifdef O_RSYNC
    799 	{ "rsync",	2,	O_RSYNC		},
    800 #else
    801 # define O_RSYNC 0
    802 #endif
    803 #ifdef O_ALT_IO
    804 	{ "altio",	2,	O_ALT_IO	},
    805 #else
    806 # define O_ALT_IO 0
    807 #endif
    808 #ifdef O_DIRECT
    809 	{ "direct",	2,	O_DIRECT	},
    810 #else
    811 # define O_DIRECT 0
    812 #endif
    813 #ifdef O_NOSIGPIPE
    814 	{ "nosigpipe",	3,	O_NOSIGPIPE	},
    815 #else
    816 # define O_NOSIGPIPE 0
    817 #endif
    818 
    819 #define ALLFLAGS (O_APPEND|O_ASYNC|O_SYNC|O_NONBLOCK|O_DSYNC|O_RSYNC|\
    820     O_ALT_IO|O_DIRECT|O_NOSIGPIPE)
    821 
    822 #ifndef	O_CLOEXEC
    823 # define O_CLOEXEC	((~ALLFLAGS) ^ ((~ALLFLAGS) & ((~ALLFLAGS) - 1)))
    824 #endif
    825 
    826 	/* for any system we support, close on exec is always defined */
    827 	{ "cloexec",	2,	O_CLOEXEC	},
    828 	{ 0, 0, 0 }
    829 };
    830 
    831 #ifndef O_ACCMODE
    832 # define O_ACCMODE	0
    833 #endif
    834 #ifndef O_RDONLY
    835 # define O_RDONLY	0
    836 #endif
    837 #ifndef O_WRONLY
    838 # define O_WRONLY	0
    839 #endif
    840 #ifndef O_RWDR
    841 # define O_RWDR		0
    842 #endif
    843 #ifndef O_SHLOCK
    844 # define O_SHLOCK	0
    845 #endif
    846 #ifndef O_EXLOCK
    847 # define O_EXLOCK	0
    848 #endif
    849 #ifndef O_NOFOLLOW
    850 # define O_NOFOLLOW	0
    851 #endif
    852 #ifndef O_CREAT
    853 # define O_CREAT	0
    854 #endif
    855 #ifndef O_TRUNC
    856 # define O_TRUNC	0
    857 #endif
    858 #ifndef O_EXCL
    859 # define O_EXCL		0
    860 #endif
    861 #ifndef O_NOCTTY
    862 # define O_NOCTTY	0
    863 #endif
    864 #ifndef O_DIRECTORY
    865 # define O_DIRECTORY	0
    866 #endif
    867 #ifndef O_REGULAR
    868 # define O_REGULAR	0
    869 #endif
    870 /*
    871  * flags that F_GETFL might return that we want to ignore
    872  *
    873  * F_GETFL should not actually return these, they're all just open()
    874  * modifiers, rather than state, but just in case...
    875  */
    876 #define IGNFLAGS (O_ACCMODE|O_RDONLY|O_WRONLY|O_RDWR|O_SHLOCK|O_EXLOCK| \
    877     O_NOFOLLOW|O_CREAT|O_TRUNC|O_EXCL|O_NOCTTY|O_DIRECTORY|O_REGULAR)
    878 
    879 static int
    880 getflags(int fd, int p)
    881 {
    882 	int c, f;
    883 
    884 	if (sh_fd(fd) != NULL || saved_redirected_fd(fd) != NULL) {
    885 		if (!p)
    886 			return -1;
    887 		error("Can't get status for fd=%d (%s)", fd, strerror(EBADF));
    888 	}
    889 
    890 	if ((c = fcntl(fd, F_GETFD)) == -1) {
    891 		if (!p)
    892 			return -1;
    893 		error("Can't get status for fd=%d (%s)", fd, strerror(errno));
    894 	}
    895 	if ((f = fcntl(fd, F_GETFL)) == -1) {
    896 		if (!p)
    897 			return -1;
    898 		error("Can't get flags for fd=%d (%s)", fd, strerror(errno));
    899 	}
    900 	f &= ~IGNFLAGS;		/* clear anything we know about, but ignore */
    901 	if (c & FD_CLOEXEC)
    902 		f |= O_CLOEXEC;
    903 	return f;
    904 }
    905 
    906 static void
    907 printone(int fd, int p, int verbose, int pfd)
    908 {
    909 	int f = getflags(fd, p);
    910 	const struct flgnames *fn;
    911 
    912 	if (f == -1)
    913 		return;
    914 
    915 	if (pfd)
    916 		outfmt(out1, "%d: ", fd);
    917 	for (fn = nv; fn->name; fn++) {
    918 		if (f & fn->value) {
    919 			outfmt(out1, "%s%s", verbose ? "+" : "", fn->name);
    920 			f &= ~fn->value;
    921 		} else if (verbose)
    922 			outfmt(out1, "-%s", fn->name);
    923 		else
    924 			continue;
    925 		if (f || (verbose && fn[1].name))
    926 			outfmt(out1, ",");
    927 	}
    928 	if (verbose && f)		/* f should be normally be 0 */
    929 		outfmt(out1, " +%#x", f);
    930 	outfmt(out1, "\n");
    931 }
    932 
    933 static void
    934 parseflags(char *s, int *p, int *n)
    935 {
    936 	int *v, *w;
    937 	const struct flgnames *fn;
    938 	size_t len;
    939 
    940 	*p = 0;
    941 	*n = 0;
    942 	for (s = strtok(s, ","); s; s = strtok(NULL, ",")) {
    943 		switch (*s++) {
    944 		case '+':
    945 			v = p;
    946 			w = n;
    947 			break;
    948 		case '-':
    949 			v = n;
    950 			w = p;
    951 			break;
    952 		default:
    953 			error("Missing +/- indicator before flag %s", s-1);
    954 		}
    955 
    956 		len = strlen(s);
    957 		for (fn = nv; fn->name; fn++)
    958 			if (len >= fn->minch && strncmp(s,fn->name,len) == 0) {
    959 				*v |= fn->value;
    960 				*w &=~ fn->value;
    961 				break;
    962 			}
    963 		if (fn->name == 0)
    964 			error("Bad flag `%s'", s);
    965 	}
    966 }
    967 
    968 static void
    969 setone(int fd, int pos, int neg, int verbose)
    970 {
    971 	int f = getflags(fd, 1);
    972 	int n, cloexec;
    973 
    974 	if (f == -1)
    975 		return;
    976 
    977 	cloexec = -1;
    978 	if ((pos & O_CLOEXEC) && !(f & O_CLOEXEC))
    979 		cloexec = FD_CLOEXEC;
    980 	if ((neg & O_CLOEXEC) && (f & O_CLOEXEC))
    981 		cloexec = 0;
    982 
    983 	if (cloexec != -1 && fcntl(fd, F_SETFD, cloexec) == -1)
    984 		error("Can't set status for fd=%d (%s)", fd, strerror(errno));
    985 
    986 	pos &= ~O_CLOEXEC;
    987 	neg &= ~O_CLOEXEC;
    988 	f &= ~O_CLOEXEC;
    989 	n = f;
    990 	n |= pos;
    991 	n &= ~neg;
    992 	if (n != f && fcntl(fd, F_SETFL, n) == -1)
    993 		error("Can't set flags for fd=%d (%s)", fd, strerror(errno));
    994 	if (verbose)
    995 		printone(fd, 1, verbose, 1);
    996 }
    997 
    998 int
    999 fdflagscmd(int argc, char *argv[])
   1000 {
   1001 	char *num;
   1002 	int verbose = 0, ch, pos = 0, neg = 0;
   1003 	char *setflags = NULL;
   1004 
   1005 	optreset = 1; optind = 1; /* initialize getopt */
   1006 	while ((ch = getopt(argc, argv, ":vs:")) != -1)
   1007 		switch ((char)ch) {
   1008 		case 'v':
   1009 			verbose = 1;
   1010 			break;
   1011 		case 's':
   1012 			if (setflags)
   1013 				goto msg;
   1014 			setflags = optarg;
   1015 			break;
   1016 		case '?':
   1017 		default:
   1018 		msg:
   1019 			error("Usage: fdflags [-v] [-s <flags> fd] [fd...]");
   1020 			/* NOTREACHED */
   1021 		}
   1022 
   1023 	argc -= optind, argv += optind;
   1024 
   1025 	if (setflags)
   1026 		parseflags(setflags, &pos, &neg);
   1027 
   1028 	if (argc == 0) {
   1029 		int i;
   1030 
   1031 		if (setflags)
   1032 			goto msg;
   1033 
   1034 		for (i = 0; i <= max_user_fd; i++)
   1035 			printone(i, 0, verbose, 1);
   1036 		return 0;
   1037 	}
   1038 
   1039 	while ((num = *argv++) != NULL) {
   1040 		int fd = number(num);
   1041 
   1042 		while (num[0] == '0' && num[1] != '\0')		/* skip 0's */
   1043 			num++;
   1044 		if (strlen(num) > 5 ||
   1045 		    (fd >= user_fd_limit && fd > max_user_fd))
   1046 			error("%s: too big to be a file descriptor", num);
   1047 
   1048 		if (setflags)
   1049 			setone(fd, pos, neg, verbose);
   1050 		else
   1051 			printone(fd, 1, verbose, argc > 1);
   1052 	}
   1053 	return 0;
   1054 }
   1055 
   1056 #undef MAX		/* in case we inherited them from somewhere */
   1057 #undef MIN
   1058 
   1059 #define	MIN(a,b)	(/*CONSTCOND*/((a)<=(b)) ? (a) : (b))
   1060 #define	MAX(a,b)	(/*CONSTCOND*/((a)>=(b)) ? (a) : (b))
   1061 
   1062 		/* now make the compiler work for us... */
   1063 #define	MIN_REDIR	MIN(MIN(MIN(MIN(NTO,NFROM), MIN(NTOFD,NFROMFD)), \
   1064 		   MIN(MIN(NCLOBBER,NAPPEND), MIN(NHERE,NXHERE))), NFROMTO)
   1065 #define	MAX_REDIR	MAX(MAX(MAX(MAX(NTO,NFROM), MAX(NTOFD,NFROMFD)), \
   1066 		   MAX(MAX(NCLOBBER,NAPPEND), MAX(NHERE,NXHERE))), NFROMTO)
   1067 
   1068 static const char *redir_sym[MAX_REDIR - MIN_REDIR + 1] = {
   1069 	[NTO      - MIN_REDIR]=	">",
   1070 	[NFROM    - MIN_REDIR]=	"<",
   1071 	[NTOFD    - MIN_REDIR]=	">&",
   1072 	[NFROMFD  - MIN_REDIR]=	"<&",
   1073 	[NCLOBBER - MIN_REDIR]=	">|",
   1074 	[NAPPEND  - MIN_REDIR]=	">>",
   1075 	[NHERE    - MIN_REDIR]=	"<<",
   1076 	[NXHERE   - MIN_REDIR]=	"<<",
   1077 	[NFROMTO  - MIN_REDIR]=	"<>",
   1078 };
   1079 
   1080 int
   1081 outredir(struct output *out, union node *n, int sep)
   1082 {
   1083 	if (n == NULL)
   1084 		return 0;
   1085 	if (n->type < MIN_REDIR || n->type > MAX_REDIR ||
   1086 	    redir_sym[n->type - MIN_REDIR] == NULL)
   1087 		return 0;
   1088 
   1089 	if (sep)
   1090 		outc(sep, out);
   1091 
   1092 	/*
   1093 	 * ugly, but all redir node types have "fd" in same slot...
   1094 	 *	(and code other places assumes it as well)
   1095 	 */
   1096 	if ((redir_sym[n->type - MIN_REDIR][0] == '<' && n->nfile.fd != 0) ||
   1097 	    (redir_sym[n->type - MIN_REDIR][0] == '>' && n->nfile.fd != 1))
   1098 		outfmt(out, "%d", n->nfile.fd);
   1099 
   1100 	outstr(redir_sym[n->type - MIN_REDIR], out);
   1101 
   1102 	switch (n->type) {
   1103 	case NHERE:
   1104 		outstr("'...'", out);
   1105 		break;
   1106 	case NXHERE:
   1107 		outstr("...", out);
   1108 		break;
   1109 	case NTOFD:
   1110 	case NFROMFD:
   1111 		if (n->ndup.dupfd < 0)
   1112 			outc('-', out);
   1113 		else
   1114 			outfmt(out, "%d", n->ndup.dupfd);
   1115 		break;
   1116 	default:
   1117 		outstr(n->nfile.expfname, out);
   1118 		break;
   1119 	}
   1120 	return 1;
   1121 }
   1122