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