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