1e3cfc8crgrimes/*-
2872b698pfg * SPDX-License-Identifier: BSD-3-Clause
3872b698pfg *
4e3cfc8crgrimes * Copyright (c) 1991, 1993
5e3cfc8crgrimes *	The Regents of the University of California.  All rights reserved.
6e3cfc8crgrimes *
7e3cfc8crgrimes * This code is derived from software contributed to Berkeley by
8e3cfc8crgrimes * Kenneth Almquist.
9e3cfc8crgrimes *
10e3cfc8crgrimes * Redistribution and use in source and binary forms, with or without
11e3cfc8crgrimes * modification, are permitted provided that the following conditions
12e3cfc8crgrimes * are met:
13e3cfc8crgrimes * 1. Redistributions of source code must retain the above copyright
14e3cfc8crgrimes *    notice, this list of conditions and the following disclaimer.
15e3cfc8crgrimes * 2. Redistributions in binary form must reproduce the above copyright
16e3cfc8crgrimes *    notice, this list of conditions and the following disclaimer in the
17e3cfc8crgrimes *    documentation and/or other materials provided with the distribution.
187e6cabdimp * 3. Neither the name of the University nor the names of its contributors
19e3cfc8crgrimes *    may be used to endorse or promote products derived from this software
20e3cfc8crgrimes *    without specific prior written permission.
21e3cfc8crgrimes *
22e3cfc8crgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23e3cfc8crgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24e3cfc8crgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25e3cfc8crgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26e3cfc8crgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27e3cfc8crgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28e3cfc8crgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29e3cfc8crgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30e3cfc8crgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31e3cfc8crgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32e3cfc8crgrimes * SUCH DAMAGE.
33e3cfc8crgrimes */
34e3cfc8crgrimes
35e3cfc8crgrimes#ifndef lint
3686bc037charnier#if 0
3786bc037charnierstatic char sccsid[] = "@(#)redir.c	8.2 (Berkeley) 5/4/95";
3886bc037charnier#endif
39e3cfc8crgrimes#endif /* not lint */
40f6f518bobrien#include <sys/cdefs.h>
41f6f518bobrien__FBSDID("$FreeBSD$");
42e3cfc8crgrimes
435195be9peter#include <sys/types.h>
44ada2f90tjr#include <sys/stat.h>
455195be9peter#include <signal.h>
465195be9peter#include <string.h>
475195be9peter#include <fcntl.h>
485195be9peter#include <errno.h>
495195be9peter#include <unistd.h>
505195be9peter#include <stdlib.h>
515195be9peter
52e3cfc8crgrimes/*
53e3cfc8crgrimes * Code for dealing with input/output redirection.
54e3cfc8crgrimes */
55e3cfc8crgrimes
56e3cfc8crgrimes#include "shell.h"
57e3cfc8crgrimes#include "nodes.h"
58e3cfc8crgrimes#include "jobs.h"
59e3cfc8crgrimes#include "expand.h"
60e3cfc8crgrimes#include "redir.h"
61e3cfc8crgrimes#include "output.h"
62e3cfc8crgrimes#include "memalloc.h"
63e3cfc8crgrimes#include "error.h"
64ada2f90tjr#include "options.h"
65e3cfc8crgrimes
66e3cfc8crgrimes
67e3cfc8crgrimes#define EMPTY -2		/* marks an unused slot in redirtab */
68171b494jilles#define CLOSED -1		/* fd was not open before redir */
69e3cfc8crgrimes
70e3cfc8crgrimes
71e3cfc8crgrimesstruct redirtab {
72e3cfc8crgrimes	struct redirtab *next;
7374e4193tjr	int renamed[10];
744e34b84jilles	int fd0_redirected;
758705203jilles	unsigned int empty_redirs;
76e3cfc8crgrimes};
77e3cfc8crgrimes
78e3cfc8crgrimes
7945d56acjillesstatic struct redirtab *redirlist;
80e3cfc8crgrimes
811888033rgrimes/*
82e3cfc8crgrimes * We keep track of whether or not fd0 has been redirected.  This is for
83e3cfc8crgrimes * background commands, where we want to redirect fd0 to /dev/null only
841888033rgrimes * if it hasn't already been redirected.
85e3cfc8crgrimes*/
86f31ad1cobrienstatic int fd0_redirected = 0;
87e3cfc8crgrimes
888705203jilles/* Number of redirtabs that have not been allocated. */
898705203jillesstatic unsigned int empty_redirs = 0;
908705203jilles
9108b8d91obrienstatic void openredirect(union node *, char[10 ]);
9208b8d91obrienstatic int openhere(union node *);
93e3cfc8crgrimes
94e3cfc8crgrimes
95e3cfc8crgrimes/*
96e3cfc8crgrimes * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
97e3cfc8crgrimes * old file descriptors are stashed away so that the redirection can be
98e3cfc8crgrimes * undone by calling popredir.  If the REDIR_BACKQ flag is set, then the
99e3cfc8crgrimes * standard output, and the standard error if it becomes a duplicate of
100e3cfc8crgrimes * stdout, is saved in memory.
101270892cjilles*
102270892cjilles * We suppress interrupts so that we won't leave open file
103270892cjilles * descriptors around.  Because the signal handler remains
104270892cjilles * installed and we do not use system call restart, interrupts
105270892cjilles * will still abort blocking opens such as fifos (they will fail
106270892cjilles * with EINTR). There is, however, a race condition if an interrupt
107270892cjilles * arrives after INTOFF and before open blocks.
108e3cfc8crgrimes */
109e3cfc8crgrimes
110e3cfc8crgrimesvoid
1115ef5088impredirect(union node *redir, int flags)
1125ef5088imp{
113e3cfc8crgrimes	union node *n;
1145195be9peter	struct redirtab *sv = NULL;
115e3cfc8crgrimes	int i;
116e3cfc8crgrimes	int fd;
117c58aca0steve	char memory[10];	/* file descriptors to write to memory */
118e3cfc8crgrimes
119270892cjilles	INTOFF;
120e3cfc8crgrimes	for (i = 10 ; --i >= 0 ; )
121e3cfc8crgrimes		memory[i] = 0;
122e3cfc8crgrimes	memory[1] = flags & REDIR_BACKQ;
123e3cfc8crgrimes	if (flags & REDIR_PUSH) {
1248705203jilles		empty_redirs++;
1258705203jilles		if (redir != NULL) {
1268705203jilles			sv = ckmalloc(sizeof (struct redirtab));
1278705203jilles			for (i = 0 ; i < 10 ; i++)
1288705203jilles				sv->renamed[i] = EMPTY;
1298705203jilles			sv->fd0_redirected = fd0_redirected;
1308705203jilles			sv->empty_redirs = empty_redirs - 1;
1318705203jilles			sv->next = redirlist;
1328705203jilles			redirlist = sv;
1338705203jilles			empty_redirs = 0;
1348705203jilles		}
135e3cfc8crgrimes	}
136e3cfc8crgrimes	for (n = redir ; n ; n = n->nfile.next) {
137e3cfc8crgrimes		fd = n->nfile.fd;
1384e34b84jilles		if (fd == 0)
1394e34b84jilles			fd0_redirected = 1;
1408deb948joerg		if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
1418deb948joerg		    n->ndup.dupfd == fd)
142c58aca0steve			continue; /* redirect from/to same file descriptor */
1431601bfasteve
144e3cfc8crgrimes		if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
145e3cfc8crgrimes			INTOFF;
1461357864jilles			if ((i = fcntl(fd, F_DUPFD_CLOEXEC, 10)) == -1) {
1471601bfasteve				switch (errno) {
1481601bfasteve				case EBADF:
149171b494jilles					i = CLOSED;
150171b494jilles					break;
1511601bfasteve				default:
1521601bfasteve					INTON;
1531601bfasteve					error("%d: %s", fd, strerror(errno));
1541601bfasteve					break;
1551601bfasteve				}
1561357864jilles			}
157171b494jilles			sv->renamed[fd] = i;
158e3cfc8crgrimes			INTON;
159e3cfc8crgrimes		}
160171b494jilles		openredirect(n, memory);
161270892cjilles		INTON;
162270892cjilles		INTOFF;
163e3cfc8crgrimes	}
164e3cfc8crgrimes	if (memory[1])
165e3cfc8crgrimes		out1 = &memout;
166e3cfc8crgrimes	if (memory[2])
167e3cfc8crgrimes		out2 = &memout;
168270892cjilles	INTON;
169e3cfc8crgrimes}
170e3cfc8crgrimes
171e3cfc8crgrimes
17208b8d91obrienstatic void
1735ef5088impopenredirect(union node *redir, char memory[10])
1745ef5088imp{
175ada2f90tjr	struct stat sb;
176e3cfc8crgrimes	int fd = redir->nfile.fd;
177eeed811jilles	const char *fname;
178e3cfc8crgrimes	int f;
179e3df947jilles	int e;
180e3cfc8crgrimes
181e3cfc8crgrimes	memory[fd] = 0;
182e3cfc8crgrimes	switch (redir->nfile.type) {
183e3cfc8crgrimes	case NFROM:
184e3cfc8crgrimes		fname = redir->nfile.expfname;
185e3cfc8crgrimes		if ((f = open(fname, O_RDONLY)) < 0)
1866307190tjr			error("cannot open %s: %s", fname, strerror(errno));
187e3cfc8crgrimes		break;
18889a0a9cbrian	case NFROMTO:
18989a0a9cbrian		fname = redir->nfile.expfname;
19089a0a9cbrian		if ((f = open(fname, O_RDWR|O_CREAT, 0666)) < 0)
1916307190tjr			error("cannot create %s: %s", fname, strerror(errno));
1928883e8ajilles		break;
193e3cfc8crgrimes	case NTO:
194e3cb9d1jilles		if (Cflag) {
195e3cb9d1jilles			fname = redir->nfile.expfname;
196e3cb9d1jilles			if (stat(fname, &sb) == -1) {
197e3cb9d1jilles				if ((f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666)) < 0)
198e3cb9d1jilles					error("cannot create %s: %s", fname, strerror(errno));
199e3cb9d1jilles			} else if (!S_ISREG(sb.st_mode)) {
200e3cb9d1jilles				if ((f = open(fname, O_WRONLY, 0666)) < 0)
201e3cb9d1jilles					error("cannot create %s: %s", fname, strerror(errno));
202e3cb9d1jilles				if (fstat(f, &sb) != -1 && S_ISREG(sb.st_mode)) {
203e3cb9d1jilles					close(f);
204e3cb9d1jilles					error("cannot create %s: %s", fname,
205e3cb9d1jilles					    strerror(EEXIST));
206e3cb9d1jilles				}
207e3cb9d1jilles			} else
208e3cb9d1jilles				error("cannot create %s: %s", fname,
209e3cb9d1jilles				    strerror(EEXIST));
2108883e8ajilles			break;
211e3cb9d1jilles		}
212e3cb9d1jilles		/* FALLTHROUGH */
213ada2f90tjr	case NCLOBBER:
214ada2f90tjr		fname = redir->nfile.expfname;
215ada2f90tjr		if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
2166307190tjr			error("cannot create %s: %s", fname, strerror(errno));
2178883e8ajilles		break;
218e3cfc8crgrimes	case NAPPEND:
219e3cfc8crgrimes		fname = redir->nfile.expfname;
220e3cfc8crgrimes		if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
2216307190tjr			error("cannot create %s: %s", fname, strerror(errno));
2228883e8ajilles		break;
223e3cfc8crgrimes	case NTOFD:
224e3cfc8crgrimes	case NFROMFD:
225e3cfc8crgrimes		if (redir->ndup.dupfd >= 0) {	/* if not ">&-" */
226e3cfc8crgrimes			if (memory[redir->ndup.dupfd])
227e3cfc8crgrimes				memory[fd] = 1;
228c487e17jilles			else {
229c487e17jilles				if (dup2(redir->ndup.dupfd, fd) < 0)
230c487e17jilles					error("%d: %s", redir->ndup.dupfd,
231c487e17jilles							strerror(errno));
232c487e17jilles			}
2335bed812des		} else {
234df20e19tjr			close(fd);
2355bed812des		}
2368883e8ajilles		return;
237e3cfc8crgrimes	case NHERE:
238e3cfc8crgrimes	case NXHERE:
239e3cfc8crgrimes		f = openhere(redir);
2408883e8ajilles		break;
241e3cfc8crgrimes	default:
242e3cfc8crgrimes		abort();
243e3cfc8crgrimes	}
2448883e8ajilles	if (f != fd) {
2458883e8ajilles		if (dup2(f, fd) == -1) {
2468883e8ajilles			e = errno;
2478883e8ajilles			close(f);
2488883e8ajilles			error("%d: %s", fd, strerror(e));
2498883e8ajilles		}
2508883e8ajilles		close(f);
2518883e8ajilles	}
252e3cfc8crgrimes}
253e3cfc8crgrimes
254e3cfc8crgrimes
255e3cfc8crgrimes/*
256e3cfc8crgrimes * Handle here documents.  Normally we fork off a process to write the
257e3cfc8crgrimes * data to a pipe.  If the document is short, we can stuff the data in
258e3cfc8crgrimes * the pipe without forking.
259e3cfc8crgrimes */
260e3cfc8crgrimes
26108b8d91obrienstatic int
2625ef5088impopenhere(union node *redir)
2635ef5088imp{
264eeed811jilles	const char *p;
265e3cfc8crgrimes	int pip[2];
2667236eb0jilles	size_t len = 0;
2677236eb0jilles	int flags;
2687236eb0jilles	ssize_t written = 0;
269e3cfc8crgrimes
270e3cfc8crgrimes	if (pipe(pip) < 0)
271903b2c8cracauer		error("Pipe call failed: %s", strerror(errno));
2726fa139djilles
2736fa139djilles	if (redir->type == NXHERE)
2746fa139djilles		p = redir->nhere.expdoc;
2756fa139djilles	else
2766fa139djilles		p = redir->nhere.doc->narg.text;
2776fa139djilles	len = strlen(p);
2787236eb0jilles	if (len == 0)
2796fa139djilles		goto out;
2807236eb0jilles	flags = fcntl(pip[1], F_GETFL, 0);
2817236eb0jilles	if (flags != -1 && fcntl(pip[1], F_SETFL, flags | O_NONBLOCK) != -1) {
2827236eb0jilles		written = write(pip[1], p, len);
2837236eb0jilles		if (written < 0)
2847236eb0jilles			written = 0;
2857236eb0jilles		if ((size_t)written == len)
2867236eb0jilles			goto out;
2877236eb0jilles		fcntl(pip[1], F_SETFL, flags);
288e3cfc8crgrimes	}
2896fa139djilles
290e3cfc8crgrimes	if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
291e3cfc8crgrimes		close(pip[0]);
292e3cfc8crgrimes		signal(SIGINT, SIG_IGN);
293e3cfc8crgrimes		signal(SIGQUIT, SIG_IGN);
294e3cfc8crgrimes		signal(SIGHUP, SIG_IGN);
295e3cfc8crgrimes		signal(SIGTSTP, SIG_IGN);
296e3cfc8crgrimes		signal(SIGPIPE, SIG_DFL);
2977236eb0jilles		xwrite(pip[1], p + written, len - written);
298e3cfc8crgrimes		_exit(0);
299e3cfc8crgrimes	}
300e3cfc8crgrimesout:
301e3cfc8crgrimes	close(pip[1]);
302e3cfc8crgrimes	return pip[0];
303e3cfc8crgrimes}
304e3cfc8crgrimes
305e3cfc8crgrimes
306e3cfc8crgrimes
307e3cfc8crgrimes/*
308e3cfc8crgrimes * Undo the effects of the last redirection.
309e3cfc8crgrimes */
310e3cfc8crgrimes
311e3cfc8crgrimesvoid
3125ef5088imppopredir(void)
3135ef5088imp{
3141601bfasteve	struct redirtab *rp = redirlist;
315e3cfc8crgrimes	int i;
316e3cfc8crgrimes
3178705203jilles	INTOFF;
3188705203jilles	if (empty_redirs > 0) {
3198705203jilles		empty_redirs--;
3208705203jilles		INTON;
3218705203jilles		return;
3228705203jilles	}
323e3cfc8crgrimes	for (i = 0 ; i < 10 ; i++) {
324e3cfc8crgrimes		if (rp->renamed[i] != EMPTY) {
325e3cfc8crgrimes			if (rp->renamed[i] >= 0) {
3265bed812des				dup2(rp->renamed[i], i);
327e3cfc8crgrimes				close(rp->renamed[i]);
3285bed812des			} else {
3295bed812des				close(i);
330e3cfc8crgrimes			}
331e3cfc8crgrimes		}
332e3cfc8crgrimes	}
3334e34b84jilles	fd0_redirected = rp->fd0_redirected;
3348705203jilles	empty_redirs = rp->empty_redirs;
335e3cfc8crgrimes	redirlist = rp->next;
336e3cfc8crgrimes	ckfree(rp);
337e3cfc8crgrimes	INTON;
338e3cfc8crgrimes}
339e3cfc8crgrimes
340e3cfc8crgrimes/* Return true if fd 0 has already been redirected at least once.  */
341e3cfc8crgrimesint
3425ef5088impfd0_redirected_p(void)
3435ef5088imp{
344e3cfc8crgrimes        return fd0_redirected != 0;
345e3cfc8crgrimes}
346e3cfc8crgrimes
347e3cfc8crgrimes/*
348e3cfc8crgrimes * Discard all saved file descriptors.
349e3cfc8crgrimes */
350e3cfc8crgrimes
351e3cfc8crgrimesvoid
3525ef5088impclearredir(void)
3535ef5088imp{
3541601bfasteve	struct redirtab *rp;
355e3cfc8crgrimes	int i;
356e3cfc8crgrimes
357e3cfc8crgrimes	for (rp = redirlist ; rp ; rp = rp->next) {
358e3cfc8crgrimes		for (i = 0 ; i < 10 ; i++) {
359e3cfc8crgrimes			if (rp->renamed[i] >= 0) {
360e3cfc8crgrimes				close(rp->renamed[i]);
361e3cfc8crgrimes			}
362e3cfc8crgrimes			rp->renamed[i] = EMPTY;
363e3cfc8crgrimes		}
364e3cfc8crgrimes	}
365e3cfc8crgrimes}
366