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