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