Home | History | Annotate | Line # | Download | only in sh
redir.c revision 1.50
      1  1.50  christos /*	$NetBSD: redir.c,v 1.50 2017/02/02 20:00:40 christos Exp $	*/
      2  1.11       cgd 
      3   1.1       cgd /*-
      4   1.7       jtc  * Copyright (c) 1991, 1993
      5   1.7       jtc  *	The Regents of the University of California.  All rights reserved.
      6   1.1       cgd  *
      7   1.1       cgd  * This code is derived from software contributed to Berkeley by
      8   1.1       cgd  * Kenneth Almquist.
      9   1.1       cgd  *
     10   1.1       cgd  * Redistribution and use in source and binary forms, with or without
     11   1.1       cgd  * modification, are permitted provided that the following conditions
     12   1.1       cgd  * are met:
     13   1.1       cgd  * 1. Redistributions of source code must retain the above copyright
     14   1.1       cgd  *    notice, this list of conditions and the following disclaimer.
     15   1.1       cgd  * 2. Redistributions in binary form must reproduce the above copyright
     16   1.1       cgd  *    notice, this list of conditions and the following disclaimer in the
     17   1.1       cgd  *    documentation and/or other materials provided with the distribution.
     18  1.28       agc  * 3. Neither the name of the University nor the names of its contributors
     19   1.1       cgd  *    may be used to endorse or promote products derived from this software
     20   1.1       cgd  *    without specific prior written permission.
     21   1.1       cgd  *
     22   1.1       cgd  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23   1.1       cgd  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24   1.1       cgd  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25   1.1       cgd  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26   1.1       cgd  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27   1.1       cgd  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28   1.1       cgd  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29   1.1       cgd  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30   1.1       cgd  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31   1.1       cgd  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32   1.1       cgd  * SUCH DAMAGE.
     33   1.1       cgd  */
     34   1.1       cgd 
     35  1.16  christos #include <sys/cdefs.h>
     36   1.1       cgd #ifndef lint
     37  1.11       cgd #if 0
     38  1.12  christos static char sccsid[] = "@(#)redir.c	8.2 (Berkeley) 5/4/95";
     39  1.11       cgd #else
     40  1.50  christos __RCSID("$NetBSD: redir.c,v 1.50 2017/02/02 20:00:40 christos Exp $");
     41  1.11       cgd #endif
     42   1.1       cgd #endif /* not lint */
     43   1.1       cgd 
     44  1.12  christos #include <sys/types.h>
     45  1.17  christos #include <sys/param.h>	/* PIPE_BUF */
     46  1.48  christos #include <sys/stat.h>
     47  1.12  christos #include <signal.h>
     48  1.12  christos #include <string.h>
     49  1.12  christos #include <fcntl.h>
     50  1.12  christos #include <errno.h>
     51  1.12  christos #include <unistd.h>
     52  1.12  christos #include <stdlib.h>
     53  1.12  christos 
     54   1.1       cgd /*
     55   1.1       cgd  * Code for dealing with input/output redirection.
     56   1.1       cgd  */
     57   1.1       cgd 
     58  1.25  christos #include "main.h"
     59  1.50  christos #include "builtins.h"
     60   1.1       cgd #include "shell.h"
     61   1.1       cgd #include "nodes.h"
     62   1.1       cgd #include "jobs.h"
     63  1.23  christos #include "options.h"
     64   1.1       cgd #include "expand.h"
     65   1.1       cgd #include "redir.h"
     66   1.1       cgd #include "output.h"
     67   1.1       cgd #include "memalloc.h"
     68   1.1       cgd #include "error.h"
     69   1.1       cgd 
     70   1.1       cgd 
     71   1.1       cgd #define EMPTY -2		/* marks an unused slot in redirtab */
     72  1.44       kre #define CLOSED -1		/* fd was not open before redir */
     73  1.17  christos #ifndef PIPE_BUF
     74  1.17  christos # define PIPESIZE 4096		/* amount of buffering in a pipe */
     75  1.17  christos #else
     76  1.17  christos # define PIPESIZE PIPE_BUF
     77  1.17  christos #endif
     78   1.1       cgd 
     79   1.1       cgd 
     80   1.1       cgd MKINIT
     81  1.43  christos struct renamelist {
     82  1.43  christos 	struct renamelist *next;
     83  1.43  christos 	int orig;
     84  1.43  christos 	int into;
     85  1.43  christos };
     86  1.43  christos 
     87  1.43  christos MKINIT
     88   1.1       cgd struct redirtab {
     89   1.1       cgd 	struct redirtab *next;
     90  1.43  christos 	struct renamelist *renamed;
     91   1.1       cgd };
     92   1.1       cgd 
     93   1.1       cgd 
     94   1.1       cgd MKINIT struct redirtab *redirlist;
     95   1.1       cgd 
     96  1.13  christos /*
     97   1.7       jtc  * We keep track of whether or not fd0 has been redirected.  This is for
     98   1.7       jtc  * background commands, where we want to redirect fd0 to /dev/null only
     99  1.13  christos  * if it hasn't already been redirected.
    100  1.43  christos  */
    101  1.43  christos STATIC int fd0_redirected = 0;
    102   1.1       cgd 
    103  1.43  christos /*
    104  1.43  christos  * And also where to put internal use fds that should be out of the
    105  1.43  christos  * way of user defined fds (normally)
    106  1.43  christos  */
    107  1.43  christos STATIC int big_sh_fd = 0;
    108  1.43  christos 
    109  1.43  christos STATIC const struct renamelist *is_renamed(const struct renamelist *, int);
    110  1.43  christos STATIC void fd_rename(struct redirtab *, int, int);
    111  1.43  christos STATIC void free_rl(struct redirtab *, int);
    112  1.29  christos STATIC void openredirect(union node *, char[10], int);
    113  1.34      yamt STATIC int openhere(const union node *);
    114  1.47       kre STATIC int copyfd(int, int, int);
    115  1.43  christos STATIC void find_big_fd(void);
    116  1.43  christos 
    117  1.43  christos STATIC const struct renamelist *
    118  1.43  christos is_renamed(const struct renamelist *rl, int fd)
    119  1.43  christos {
    120  1.43  christos 	while (rl != NULL) {
    121  1.43  christos 		if (rl->orig == fd)
    122  1.43  christos 			return rl;
    123  1.43  christos 		rl = rl->next;
    124  1.43  christos 	}
    125  1.43  christos 	return NULL;
    126  1.43  christos }
    127  1.43  christos 
    128  1.43  christos STATIC void
    129  1.43  christos free_rl(struct redirtab *rt, int reset)
    130  1.43  christos {
    131  1.43  christos 	struct renamelist *rl, *rn = rt->renamed;
    132  1.43  christos 
    133  1.43  christos 	while ((rl = rn) != NULL) {
    134  1.43  christos 		rn = rl->next;
    135  1.43  christos 		if (rl->orig == 0)
    136  1.43  christos 			fd0_redirected--;
    137  1.43  christos 		if (reset) {
    138  1.43  christos 			if (rl->into < 0)
    139  1.43  christos 				close(rl->orig);
    140  1.43  christos 			else
    141  1.43  christos 				movefd(rl->into, rl->orig);
    142  1.43  christos 		}
    143  1.43  christos 		ckfree(rl);
    144  1.43  christos 	}
    145  1.43  christos 	rt->renamed = NULL;
    146  1.43  christos }
    147   1.1       cgd 
    148  1.43  christos STATIC void
    149  1.43  christos fd_rename(struct redirtab *rt, int from, int to)
    150  1.43  christos {
    151  1.43  christos 	struct renamelist *rl = ckmalloc(sizeof(struct renamelist));
    152  1.43  christos 
    153  1.43  christos 	rl->next = rt->renamed;
    154  1.43  christos 	rt->renamed = rl;
    155  1.43  christos 
    156  1.43  christos 	rl->orig = from;
    157  1.43  christos 	rl->into = to;
    158  1.43  christos }
    159   1.1       cgd 
    160   1.1       cgd /*
    161   1.1       cgd  * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
    162   1.1       cgd  * old file descriptors are stashed away so that the redirection can be
    163   1.1       cgd  * undone by calling popredir.  If the REDIR_BACKQ flag is set, then the
    164   1.1       cgd  * standard output, and the standard error if it becomes a duplicate of
    165   1.1       cgd  * stdout, is saved in memory.
    166   1.1       cgd  */
    167   1.1       cgd 
    168   1.1       cgd void
    169  1.27  christos redirect(union node *redir, int flags)
    170  1.27  christos {
    171   1.1       cgd 	union node *n;
    172  1.16  christos 	struct redirtab *sv = NULL;
    173   1.1       cgd 	int i;
    174   1.1       cgd 	int fd;
    175  1.13  christos 	char memory[10];	/* file descriptors to write to memory */
    176   1.1       cgd 
    177   1.1       cgd 	for (i = 10 ; --i >= 0 ; )
    178   1.1       cgd 		memory[i] = 0;
    179   1.1       cgd 	memory[1] = flags & REDIR_BACKQ;
    180   1.1       cgd 	if (flags & REDIR_PUSH) {
    181  1.24  christos 		/* We don't have to worry about REDIR_VFORK here, as
    182  1.24  christos 		 * flags & REDIR_PUSH is never true if REDIR_VFORK is set.
    183  1.24  christos 		 */
    184   1.1       cgd 		sv = ckmalloc(sizeof (struct redirtab));
    185  1.43  christos 		sv->renamed = NULL;
    186   1.1       cgd 		sv->next = redirlist;
    187   1.1       cgd 		redirlist = sv;
    188   1.1       cgd 	}
    189   1.1       cgd 	for (n = redir ; n ; n = n->nfile.next) {
    190   1.1       cgd 		fd = n->nfile.fd;
    191  1.13  christos 		if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
    192  1.43  christos 		    n->ndup.dupfd == fd) {
    193  1.43  christos 			/* redirect from/to same file descriptor */
    194  1.47       kre 			/* make sure it stays open */
    195  1.47       kre 			if (fcntl(fd, F_SETFD, 0) < 0)
    196  1.47       kre 				error("fd %d: %s", fd, strerror(errno));
    197  1.43  christos 			continue;
    198  1.43  christos 		}
    199  1.15  christos 
    200  1.43  christos 		if ((flags & REDIR_PUSH) && !is_renamed(sv->renamed, fd)) {
    201   1.1       cgd 			INTOFF;
    202  1.43  christos 			if (big_sh_fd < 10)
    203  1.43  christos 				find_big_fd();
    204  1.43  christos 			if ((i = fcntl(fd, F_DUPFD, big_sh_fd)) == -1) {
    205  1.15  christos 				switch (errno) {
    206  1.15  christos 				case EBADF:
    207  1.35      yamt 					i = CLOSED;
    208  1.35      yamt 					break;
    209  1.43  christos 				case EMFILE:
    210  1.43  christos 				case EINVAL:
    211  1.43  christos 					find_big_fd();
    212  1.43  christos 					i = fcntl(fd, F_DUPFD, big_sh_fd);
    213  1.43  christos 					if (i >= 0)
    214  1.43  christos 						break;
    215  1.43  christos 					/* FALLTHRU */
    216  1.15  christos 				default:
    217  1.43  christos 					i = errno;
    218  1.43  christos 					INTON;    /* XXX not needed here ? */
    219  1.43  christos 					error("%d: %s", fd, strerror(i));
    220  1.19   mycroft 					/* NOTREACHED */
    221  1.15  christos 				}
    222  1.43  christos 			}
    223  1.43  christos 			if (i >= 0)
    224  1.35      yamt 				(void)fcntl(i, F_SETFD, FD_CLOEXEC);
    225  1.43  christos 			fd_rename(sv, fd, i);
    226   1.1       cgd 			INTON;
    227   1.1       cgd 		}
    228  1.44       kre 		if (fd == 0)
    229  1.44       kre 			fd0_redirected++;
    230  1.35      yamt 		openredirect(n, memory, flags);
    231   1.1       cgd 	}
    232   1.1       cgd 	if (memory[1])
    233   1.1       cgd 		out1 = &memout;
    234   1.1       cgd 	if (memory[2])
    235   1.1       cgd 		out2 = &memout;
    236   1.1       cgd }
    237   1.1       cgd 
    238   1.1       cgd 
    239   1.1       cgd STATIC void
    240  1.29  christos openredirect(union node *redir, char memory[10], int flags)
    241  1.27  christos {
    242  1.36  christos 	struct stat sb;
    243   1.1       cgd 	int fd = redir->nfile.fd;
    244   1.1       cgd 	char *fname;
    245   1.1       cgd 	int f;
    246  1.42  christos 	int eflags, cloexec;
    247   1.1       cgd 
    248   1.1       cgd 	/*
    249   1.1       cgd 	 * We suppress interrupts so that we won't leave open file
    250   1.1       cgd 	 * descriptors around.  This may not be such a good idea because
    251   1.1       cgd 	 * an open of a device or a fifo can block indefinitely.
    252   1.1       cgd 	 */
    253   1.1       cgd 	INTOFF;
    254  1.43  christos 	if (fd < 10)
    255  1.43  christos 		memory[fd] = 0;
    256   1.1       cgd 	switch (redir->nfile.type) {
    257   1.1       cgd 	case NFROM:
    258   1.1       cgd 		fname = redir->nfile.expfname;
    259  1.29  christos 		if (flags & REDIR_VFORK)
    260  1.29  christos 			eflags = O_NONBLOCK;
    261  1.29  christos 		else
    262  1.29  christos 			eflags = 0;
    263  1.29  christos 		if ((f = open(fname, O_RDONLY|eflags)) < 0)
    264  1.20  christos 			goto eopen;
    265  1.29  christos 		if (eflags)
    266  1.29  christos 			(void)fcntl(f, F_SETFL, fcntl(f, F_GETFL, 0) & ~eflags);
    267  1.20  christos 		break;
    268  1.20  christos 	case NFROMTO:
    269  1.20  christos 		fname = redir->nfile.expfname;
    270  1.20  christos 		if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
    271  1.20  christos 			goto ecreate;
    272   1.1       cgd 		break;
    273   1.1       cgd 	case NTO:
    274  1.36  christos 		if (Cflag) {
    275  1.36  christos 			fname = redir->nfile.expfname;
    276  1.37  christos 			if ((f = open(fname, O_WRONLY)) == -1) {
    277  1.36  christos 				if ((f = open(fname, O_WRONLY|O_CREAT|O_EXCL,
    278  1.36  christos 				    0666)) < 0)
    279  1.36  christos 					goto ecreate;
    280  1.37  christos 			} else if (fstat(f, &sb) == -1) {
    281  1.37  christos 				int serrno = errno;
    282  1.37  christos 				close(f);
    283  1.37  christos 				errno = serrno;
    284  1.37  christos 				goto ecreate;
    285  1.37  christos 			} else if (S_ISREG(sb.st_mode)) {
    286  1.37  christos 				close(f);
    287  1.36  christos 				errno = EEXIST;
    288  1.36  christos 				goto ecreate;
    289  1.36  christos 			}
    290  1.36  christos 			break;
    291  1.36  christos 		}
    292  1.23  christos 		/* FALLTHROUGH */
    293  1.23  christos 	case NCLOBBER:
    294   1.1       cgd 		fname = redir->nfile.expfname;
    295  1.36  christos 		if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
    296  1.20  christos 			goto ecreate;
    297  1.20  christos 		break;
    298   1.1       cgd 	case NAPPEND:
    299   1.1       cgd 		fname = redir->nfile.expfname;
    300   1.1       cgd 		if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
    301  1.20  christos 			goto ecreate;
    302  1.20  christos 		break;
    303   1.1       cgd 	case NTOFD:
    304   1.1       cgd 	case NFROMFD:
    305   1.1       cgd 		if (redir->ndup.dupfd >= 0) {	/* if not ">&-" */
    306  1.43  christos 			if (fd < 10 && redir->ndup.dupfd < 10 &&
    307  1.43  christos 			    memory[redir->ndup.dupfd])
    308   1.1       cgd 				memory[fd] = 1;
    309  1.47       kre 			else if (copyfd(redir->ndup.dupfd, fd,
    310  1.49  christos 			    (flags & REDIR_KEEP) == 0) < 0)
    311  1.47       kre 				error("Redirect (from %d to %d) failed: %s",
    312  1.47       kre 				    redir->ndup.dupfd, fd, strerror(errno));
    313  1.45       kre 		} else
    314  1.47       kre 			(void) close(fd);
    315  1.20  christos 		INTON;
    316  1.20  christos 		return;
    317   1.1       cgd 	case NHERE:
    318   1.1       cgd 	case NXHERE:
    319   1.1       cgd 		f = openhere(redir);
    320  1.20  christos 		break;
    321   1.1       cgd 	default:
    322   1.1       cgd 		abort();
    323   1.1       cgd 	}
    324  1.20  christos 
    325  1.42  christos 	cloexec = fd > 2 && (flags & REDIR_KEEP) == 0;
    326  1.20  christos 	if (f != fd) {
    327  1.47       kre 		if (copyfd(f, fd, cloexec) < 0) {
    328  1.47       kre 			int e = errno;
    329  1.47       kre 
    330  1.47       kre 			close(f);
    331  1.47       kre 			error("redirect reassignment (fd %d) failed: %s", fd,
    332  1.47       kre 			    strerror(e));
    333  1.47       kre 		}
    334  1.20  christos 		close(f);
    335  1.42  christos 	} else if (cloexec)
    336  1.38  christos 		(void)fcntl(f, F_SETFD, FD_CLOEXEC);
    337  1.38  christos 
    338   1.1       cgd 	INTON;
    339  1.20  christos 	return;
    340  1.20  christos ecreate:
    341  1.30   msaitoh 	exerrno = 1;
    342  1.20  christos 	error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
    343  1.20  christos eopen:
    344  1.30   msaitoh 	exerrno = 1;
    345  1.20  christos 	error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
    346   1.1       cgd }
    347   1.1       cgd 
    348   1.1       cgd 
    349   1.1       cgd /*
    350   1.1       cgd  * Handle here documents.  Normally we fork off a process to write the
    351   1.1       cgd  * data to a pipe.  If the document is short, we can stuff the data in
    352   1.1       cgd  * the pipe without forking.
    353   1.1       cgd  */
    354   1.1       cgd 
    355   1.1       cgd STATIC int
    356  1.34      yamt openhere(const union node *redir)
    357  1.27  christos {
    358   1.1       cgd 	int pip[2];
    359  1.12  christos 	int len = 0;
    360   1.1       cgd 
    361   1.1       cgd 	if (pipe(pip) < 0)
    362   1.1       cgd 		error("Pipe call failed");
    363   1.1       cgd 	if (redir->type == NHERE) {
    364   1.1       cgd 		len = strlen(redir->nhere.doc->narg.text);
    365   1.1       cgd 		if (len <= PIPESIZE) {
    366   1.1       cgd 			xwrite(pip[1], redir->nhere.doc->narg.text, len);
    367   1.1       cgd 			goto out;
    368   1.1       cgd 		}
    369   1.1       cgd 	}
    370  1.32    plunky 	if (forkshell(NULL, NULL, FORK_NOJOB) == 0) {
    371   1.1       cgd 		close(pip[0]);
    372   1.1       cgd 		signal(SIGINT, SIG_IGN);
    373   1.1       cgd 		signal(SIGQUIT, SIG_IGN);
    374   1.1       cgd 		signal(SIGHUP, SIG_IGN);
    375   1.1       cgd #ifdef SIGTSTP
    376   1.1       cgd 		signal(SIGTSTP, SIG_IGN);
    377   1.1       cgd #endif
    378   1.1       cgd 		signal(SIGPIPE, SIG_DFL);
    379   1.1       cgd 		if (redir->type == NHERE)
    380   1.1       cgd 			xwrite(pip[1], redir->nhere.doc->narg.text, len);
    381   1.1       cgd 		else
    382   1.1       cgd 			expandhere(redir->nhere.doc, pip[1]);
    383   1.1       cgd 		_exit(0);
    384   1.1       cgd 	}
    385   1.1       cgd out:
    386   1.1       cgd 	close(pip[1]);
    387   1.1       cgd 	return pip[0];
    388   1.1       cgd }
    389   1.1       cgd 
    390   1.1       cgd 
    391   1.1       cgd 
    392   1.1       cgd /*
    393   1.1       cgd  * Undo the effects of the last redirection.
    394   1.1       cgd  */
    395   1.1       cgd 
    396   1.1       cgd void
    397  1.27  christos popredir(void)
    398  1.27  christos {
    399  1.14       tls 	struct redirtab *rp = redirlist;
    400   1.1       cgd 
    401   1.1       cgd 	INTOFF;
    402  1.43  christos 	free_rl(rp, 1);
    403   1.1       cgd 	redirlist = rp->next;
    404   1.1       cgd 	ckfree(rp);
    405   1.1       cgd 	INTON;
    406   1.1       cgd }
    407   1.1       cgd 
    408   1.1       cgd /*
    409   1.1       cgd  * Undo all redirections.  Called on error or interrupt.
    410   1.1       cgd  */
    411   1.1       cgd 
    412   1.1       cgd #ifdef mkinit
    413   1.1       cgd 
    414   1.1       cgd INCLUDE "redir.h"
    415   1.1       cgd 
    416   1.1       cgd RESET {
    417   1.1       cgd 	while (redirlist)
    418   1.1       cgd 		popredir();
    419   1.1       cgd }
    420   1.1       cgd 
    421   1.1       cgd SHELLPROC {
    422  1.24  christos 	clearredir(0);
    423   1.1       cgd }
    424   1.1       cgd 
    425   1.1       cgd #endif
    426   1.1       cgd 
    427   1.7       jtc /* Return true if fd 0 has already been redirected at least once.  */
    428   1.7       jtc int
    429  1.43  christos fd0_redirected_p(void)
    430  1.43  christos {
    431  1.44       kre 	return fd0_redirected != 0;
    432   1.7       jtc }
    433   1.1       cgd 
    434   1.1       cgd /*
    435   1.1       cgd  * Discard all saved file descriptors.
    436   1.1       cgd  */
    437   1.1       cgd 
    438   1.1       cgd void
    439  1.33      matt clearredir(int vforked)
    440  1.24  christos {
    441  1.14       tls 	struct redirtab *rp;
    442  1.43  christos 	struct renamelist *rl;
    443   1.1       cgd 
    444   1.1       cgd 	for (rp = redirlist ; rp ; rp = rp->next) {
    445  1.43  christos 		if (!vforked)
    446  1.43  christos 			free_rl(rp, 0);
    447  1.43  christos 		else for (rl = rp->renamed; rl; rl = rl->next)
    448  1.43  christos 			if (rl->into >= 0)
    449  1.43  christos 				close(rl->into);
    450   1.1       cgd 	}
    451   1.1       cgd }
    452   1.1       cgd 
    453   1.1       cgd 
    454   1.1       cgd 
    455   1.1       cgd /*
    456  1.47       kre  * Copy a file descriptor to be == to.
    457  1.47       kre  * cloexec indicates if we want close-on-exec or not.
    458  1.47       kre  * Returns -1 if any error occurs.
    459   1.1       cgd  */
    460   1.1       cgd 
    461  1.47       kre STATIC int
    462  1.47       kre copyfd(int from, int to, int cloexec)
    463   1.9       cgd {
    464   1.1       cgd 	int newfd;
    465   1.1       cgd 
    466  1.47       kre 	if (cloexec && to > 2)
    467  1.47       kre 		newfd = dup3(from, to, O_CLOEXEC);
    468  1.47       kre 	else
    469  1.47       kre 		newfd = dup2(from, to);
    470  1.47       kre 
    471   1.1       cgd 	return newfd;
    472   1.1       cgd }
    473  1.43  christos 
    474  1.47       kre /*
    475  1.47       kre  * rename fd from to be fd to (closing from).
    476  1.47       kre  * close-on-exec is never set on 'to' (unless
    477  1.47       kre  * from==to and it was set on from) - ie: a no-op
    478  1.47       kre  * returns to (or errors() if an error occurs).
    479  1.47       kre  *
    480  1.47       kre  * This is mostly used for rearranging the
    481  1.47       kre  * results from pipe().
    482  1.47       kre  */
    483  1.43  christos int
    484  1.43  christos movefd(int from, int to)
    485  1.43  christos {
    486  1.43  christos 	if (from == to)
    487  1.43  christos 		return to;
    488  1.43  christos 
    489  1.43  christos 	(void) close(to);
    490  1.47       kre 	if (copyfd(from, to, 0) != to) {
    491  1.47       kre 		int e = errno;
    492  1.47       kre 
    493  1.47       kre 		(void) close(from);
    494  1.47       kre 		error("Unable to make fd %d: %s", to, strerror(e));
    495  1.47       kre 	}
    496  1.43  christos 	(void) close(from);
    497  1.43  christos 
    498  1.43  christos 	return to;
    499  1.43  christos }
    500  1.43  christos 
    501  1.43  christos STATIC void
    502  1.43  christos find_big_fd(void)
    503  1.43  christos {
    504  1.43  christos 	int i, fd;
    505  1.43  christos 
    506  1.43  christos 	for (i = (1 << 10); i >= 10; i >>= 1) {
    507  1.43  christos 		if ((fd = fcntl(0, F_DUPFD, i - 1)) >= 0) {
    508  1.43  christos 			close(fd);
    509  1.43  christos 			break;
    510  1.43  christos 		}
    511  1.43  christos 	}
    512  1.43  christos 
    513  1.43  christos 	fd = (i / 5) * 4;
    514  1.43  christos 	if ((i - fd) > 100)
    515  1.43  christos 		fd = i - 100;
    516  1.43  christos 	else if (fd < 10)
    517  1.43  christos 		fd = 10;
    518  1.43  christos 
    519  1.43  christos 	big_sh_fd = fd;
    520  1.43  christos }
    521  1.43  christos 
    522  1.47       kre /*
    523  1.47       kre  * If possible, move file descriptor fd out of the way
    524  1.47       kre  * of expected user fd values.   Returns the new fd
    525  1.47       kre  * (which may be the input fd if things do not go well.)
    526  1.47       kre  * Always set close-on-exec on the result, and close
    527  1.47       kre  * the input fd unless it is to be our result.
    528  1.47       kre  */
    529  1.43  christos int
    530  1.43  christos to_upper_fd(int fd)
    531  1.43  christos {
    532  1.43  christos 	int i;
    533  1.43  christos 
    534  1.43  christos 	if (big_sh_fd < 10)
    535  1.43  christos 		find_big_fd();
    536  1.43  christos 	do {
    537  1.46       kre 		i = fcntl(fd, F_DUPFD_CLOEXEC, big_sh_fd);
    538  1.43  christos 		if (i >= 0) {
    539  1.43  christos 			if (fd != i)
    540  1.43  christos 				close(fd);
    541  1.43  christos 			return i;
    542  1.43  christos 		}
    543  1.43  christos 		if (errno != EMFILE)
    544  1.43  christos 			break;
    545  1.43  christos 		find_big_fd();
    546  1.43  christos 	} while (big_sh_fd > 10);
    547  1.43  christos 
    548  1.46       kre 	/*
    549  1.47       kre 	 * If we wanted to move this fd to some random high number
    550  1.46       kre 	 * we certainly do not intend to pass it through exec, even
    551  1.46       kre 	 * if the reassignment failed.
    552  1.46       kre 	 */
    553  1.46       kre 	(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
    554  1.43  christos 	return fd;
    555  1.43  christos }
    556  1.50  christos 
    557  1.50  christos static const struct {
    558  1.50  christos 	const char *name;
    559  1.50  christos 	uint32_t value;
    560  1.50  christos } nv[] = {
    561  1.50  christos #ifdef O_APPEND
    562  1.50  christos 	{ "append",	O_APPEND 	},
    563  1.50  christos #endif
    564  1.50  christos #ifdef O_ASYNC
    565  1.50  christos 	{ "async",	O_ASYNC		},
    566  1.50  christos #endif
    567  1.50  christos #ifdef O_SYNC
    568  1.50  christos 	{ "sync",	O_SYNC		},
    569  1.50  christos #endif
    570  1.50  christos #ifdef O_NONBLOCK
    571  1.50  christos 	{ "nonblock",	O_NONBLOCK	},
    572  1.50  christos #endif
    573  1.50  christos #ifdef O_FSYNC
    574  1.50  christos 	{ "fsync",	O_FSYNC		},
    575  1.50  christos #endif
    576  1.50  christos #ifdef O_DSYNC
    577  1.50  christos 	{ "dsync",	O_DSYNC		},
    578  1.50  christos #endif
    579  1.50  christos #ifdef O_RSYNC
    580  1.50  christos 	{ "rsync",	O_RSYNC		},
    581  1.50  christos #endif
    582  1.50  christos #ifdef O_ALTIO
    583  1.50  christos 	{ "altio",	O_ALT_IO	},
    584  1.50  christos #endif
    585  1.50  christos #ifdef O_DIRECT
    586  1.50  christos 	{ "direct",	O_DIRECT	},
    587  1.50  christos #endif
    588  1.50  christos #ifdef O_NOSIGPIPE
    589  1.50  christos 	{ "nosigpipe",	O_NOSIGPIPE	},
    590  1.50  christos #endif
    591  1.50  christos #ifdef O_CLOEXEC
    592  1.50  christos 	{ "cloexec",	O_CLOEXEC	},
    593  1.50  christos #endif
    594  1.50  christos };
    595  1.50  christos #define ALLFLAGS (O_APPEND|O_ASYNC|O_SYNC|O_NONBLOCK|O_DSYNC|O_RSYNC|\
    596  1.50  christos     O_ALT_IO|O_DIRECT|O_NOSIGPIPE|O_CLOEXEC)
    597  1.50  christos 
    598  1.50  christos static int
    599  1.50  christos getflags(int fd, int p)
    600  1.50  christos {
    601  1.50  christos 	int c, f;
    602  1.50  christos 
    603  1.50  christos 	if ((c = fcntl(fd, F_GETFD)) == -1) {
    604  1.50  christos 		if (!p)
    605  1.50  christos 			return -1;
    606  1.50  christos 		error("Can't get status for fd=%d (%s)", fd, strerror(errno));
    607  1.50  christos 	}
    608  1.50  christos 	if ((f = fcntl(fd, F_GETFL)) == -1) {
    609  1.50  christos 		if (!p)
    610  1.50  christos 			return -1;
    611  1.50  christos 		error("Can't get flags for fd=%d (%s)", fd, strerror(errno));
    612  1.50  christos 	}
    613  1.50  christos 	if (c)
    614  1.50  christos 		f |= O_CLOEXEC;
    615  1.50  christos 	return f & ALLFLAGS;
    616  1.50  christos }
    617  1.50  christos 
    618  1.50  christos static void
    619  1.50  christos printone(int fd, int p, int verbose)
    620  1.50  christos {
    621  1.50  christos 	int f = getflags(fd, p);
    622  1.50  christos 
    623  1.50  christos 	if (f == -1)
    624  1.50  christos 		return;
    625  1.50  christos 
    626  1.50  christos 	outfmt(out1, "%d:", fd);
    627  1.50  christos 	for (size_t i = 0; i < __arraycount(nv); i++) {
    628  1.50  christos 		if (f & nv[i].value) {
    629  1.50  christos 			outfmt(out1, "%s%s", verbose ? "+" : "", nv[i].name);
    630  1.50  christos 			f &= ~nv[i].value;
    631  1.50  christos 		} else if (verbose)
    632  1.50  christos 			outfmt(out1, "-%s", nv[i].name);
    633  1.50  christos 		else
    634  1.50  christos 			continue;
    635  1.50  christos 		if (f || (verbose && i != __arraycount(nv) - 1))
    636  1.50  christos 			outfmt(out1, ",");
    637  1.50  christos 	}
    638  1.50  christos 	outfmt(out1, "\n");
    639  1.50  christos }
    640  1.50  christos 
    641  1.50  christos static int
    642  1.50  christos parseflags(char *s, int *p, int *n)
    643  1.50  christos {
    644  1.50  christos 	int f = 0, *v;
    645  1.50  christos 
    646  1.50  christos 	*p = 0;
    647  1.50  christos 	*n = 0;
    648  1.50  christos 	for (s = strtok(s, ","); s; s = strtok(NULL, ",")) {
    649  1.50  christos 		size_t i;
    650  1.50  christos 		switch (*s) {
    651  1.50  christos 		case '+':
    652  1.50  christos 			v = p;
    653  1.50  christos 			s++;
    654  1.50  christos 			break;
    655  1.50  christos 		case '-':
    656  1.50  christos 			v = n;
    657  1.50  christos 			s++;
    658  1.50  christos 			break;
    659  1.50  christos 		default:
    660  1.50  christos 			v = &f;
    661  1.50  christos 			break;
    662  1.50  christos 		}
    663  1.50  christos 
    664  1.50  christos 		for (i = 0; i < __arraycount(nv); i++)
    665  1.50  christos 			if (strcmp(s, nv[i].name) == 0) {
    666  1.50  christos 				*v |= nv[i].value;
    667  1.50  christos 				break;
    668  1.50  christos 			}
    669  1.50  christos 		if (i == __arraycount(nv))
    670  1.50  christos 			error("Bad flag `%s'", s);
    671  1.50  christos 	}
    672  1.50  christos 	return f;
    673  1.50  christos }
    674  1.50  christos 
    675  1.50  christos static void
    676  1.50  christos setone(int fd, int pos, int neg, int verbose)
    677  1.50  christos {
    678  1.50  christos 	int f = getflags(fd, 1);
    679  1.50  christos 	if (f == -1)
    680  1.50  christos 		return;
    681  1.50  christos 
    682  1.50  christos 	int cloexec = -1;
    683  1.50  christos 	if ((pos & O_CLOEXEC) && !(f & O_CLOEXEC))
    684  1.50  christos 		cloexec = FD_CLOEXEC;
    685  1.50  christos 	if ((neg & O_CLOEXEC) && (f & O_CLOEXEC))
    686  1.50  christos 		cloexec = 0;
    687  1.50  christos 
    688  1.50  christos 	if (cloexec != -1 && fcntl(fd, F_SETFD, cloexec) == -1)
    689  1.50  christos 		error("Can't set status for fd=%d (%s)", fd, strerror(errno));
    690  1.50  christos 
    691  1.50  christos 	pos &= ~O_CLOEXEC;
    692  1.50  christos 	neg &= ~O_CLOEXEC;
    693  1.50  christos 	f &= ~O_CLOEXEC;
    694  1.50  christos 	int n = f;
    695  1.50  christos 	n |= pos;
    696  1.50  christos 	n &= ~neg;
    697  1.50  christos 	if (n != f && fcntl(fd, F_SETFL, n) == -1)
    698  1.50  christos 		error("Can't set flags for fd=%d (%s)", fd, strerror(errno));
    699  1.50  christos 	if (verbose)
    700  1.50  christos 		printone(fd, 1, verbose);
    701  1.50  christos }
    702  1.50  christos 
    703  1.50  christos int
    704  1.50  christos fdflagscmd(int argc, char *argv[])
    705  1.50  christos {
    706  1.50  christos 	char *num;
    707  1.50  christos 	int verbose = 0, ch, pos = 0, neg = 0;
    708  1.50  christos 	char *setflags = NULL;
    709  1.50  christos 
    710  1.50  christos 	optreset = 1; optind = 1; /* initialize getopt */
    711  1.50  christos 	while ((ch = getopt(argc, argv, ":vs:")) != -1)
    712  1.50  christos 		switch ((char)ch) {
    713  1.50  christos 		case 'v':
    714  1.50  christos 			verbose = 1;
    715  1.50  christos 			break;
    716  1.50  christos 		case 's':
    717  1.50  christos 			setflags = optarg;
    718  1.50  christos 			break;
    719  1.50  christos 		case '?':
    720  1.50  christos 		default:
    721  1.50  christos 		msg:
    722  1.50  christos 			error("Usage: fdflags [-v] [-s <flags>] [fd...]");
    723  1.50  christos 			/* NOTREACHED */
    724  1.50  christos 		}
    725  1.50  christos 
    726  1.50  christos 	argc -= optind, argv += optind;
    727  1.50  christos 
    728  1.50  christos 	if (setflags && parseflags(setflags, &pos, &neg))
    729  1.50  christos 		error("Need + or - before flags");
    730  1.50  christos 
    731  1.50  christos 	if (argc == 0) {
    732  1.50  christos 		if (setflags)
    733  1.50  christos 			goto msg;
    734  1.50  christos 		int maxfd = fcntl(0, F_MAXFD);
    735  1.50  christos 		if (maxfd == -1)
    736  1.50  christos 			error("Can't get max fd (%s)", strerror(errno));
    737  1.50  christos 		for (int i = 0; i <= maxfd; i++)
    738  1.50  christos 			printone(i, 0, verbose);
    739  1.50  christos 		return 0;
    740  1.50  christos 	}
    741  1.50  christos 
    742  1.50  christos 	while ((num = *argv++) != NULL) {
    743  1.50  christos 		int e;
    744  1.50  christos 		int fd = (int)strtoi(num, NULL, 0, 0, INT_MAX, &e);
    745  1.50  christos 		if (e)
    746  1.50  christos 			error("Can't parse `%s' (%s)", num, strerror(e));
    747  1.50  christos 		if (setflags)
    748  1.50  christos 			setone(fd, pos, neg, verbose);
    749  1.50  christos 		else
    750  1.50  christos 			printone(fd, 1, verbose);
    751  1.50  christos 	}
    752  1.50  christos 	return 0;
    753  1.50  christos }
    754