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