redir.c revision 1557
1/*-
2 * Copyright (c) 1991, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 *    must display the following acknowledgement:
18 *	This product includes software developed by the University of
19 *	California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#ifndef lint
38static char sccsid[] = "@(#)redir.c	8.1 (Berkeley) 5/31/93";
39#endif /* not lint */
40
41/*
42 * Code for dealing with input/output redirection.
43 */
44
45#include "shell.h"
46#include "nodes.h"
47#include "jobs.h"
48#include "expand.h"
49#include "redir.h"
50#include "output.h"
51#include "memalloc.h"
52#include "error.h"
53#include <sys/types.h>
54#include <signal.h>
55#include <fcntl.h>
56#include <errno.h>
57#include <unistd.h>
58
59
60#define EMPTY -2		/* marks an unused slot in redirtab */
61#define PIPESIZE 4096		/* amount of buffering in a pipe */
62
63
64MKINIT
65struct redirtab {
66	struct redirtab *next;
67	short renamed[10];
68};
69
70
71MKINIT struct redirtab *redirlist;
72
73/*
74 * We keep track of whether or not fd0 has been redirected.  This is for
75 * background commands, where we want to redirect fd0 to /dev/null only
76 * if it hasn't already been redirected.
77*/
78int fd0_redirected = 0;
79
80#ifdef __STDC__
81STATIC void openredirect(union node *, char *);
82STATIC int openhere(union node *);
83#else
84STATIC void openredirect();
85STATIC int openhere();
86#endif
87
88
89
90/*
91 * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
92 * old file descriptors are stashed away so that the redirection can be
93 * undone by calling popredir.  If the REDIR_BACKQ flag is set, then the
94 * standard output, and the standard error if it becomes a duplicate of
95 * stdout, is saved in memory.
96 */
97
98void
99redirect(redir, flags)
100	union node *redir;
101	int flags;
102	{
103	union node *n;
104	struct redirtab *sv;
105	int i;
106	int fd;
107	char memory[10];		/* file descriptors to write to memory */
108
109	for (i = 10 ; --i >= 0 ; )
110		memory[i] = 0;
111	memory[1] = flags & REDIR_BACKQ;
112	if (flags & REDIR_PUSH) {
113		sv = ckmalloc(sizeof (struct redirtab));
114		for (i = 0 ; i < 10 ; i++)
115			sv->renamed[i] = EMPTY;
116		sv->next = redirlist;
117		redirlist = sv;
118	}
119	for (n = redir ; n ; n = n->nfile.next) {
120		fd = n->nfile.fd;
121		if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
122			INTOFF;
123			if ((i = copyfd(fd, 10)) != EMPTY) {
124				sv->renamed[fd] = i;
125				close(fd);
126			}
127			INTON;
128			if (i == EMPTY)
129				error("Out of file descriptors");
130		} else {
131			close(fd);
132		}
133                if (fd == 0)
134                        fd0_redirected++;
135		openredirect(n, memory);
136	}
137	if (memory[1])
138		out1 = &memout;
139	if (memory[2])
140		out2 = &memout;
141}
142
143
144STATIC void
145openredirect(redir, memory)
146	union node *redir;
147	char memory[10];
148	{
149	int fd = redir->nfile.fd;
150	char *fname;
151	int f;
152
153	/*
154	 * We suppress interrupts so that we won't leave open file
155	 * descriptors around.  This may not be such a good idea because
156	 * an open of a device or a fifo can block indefinitely.
157	 */
158	INTOFF;
159	memory[fd] = 0;
160	switch (redir->nfile.type) {
161	case NFROM:
162		fname = redir->nfile.expfname;
163		if ((f = open(fname, O_RDONLY)) < 0)
164			error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
165movefd:
166		if (f != fd) {
167			copyfd(f, fd);
168			close(f);
169		}
170		break;
171	case NTO:
172		fname = redir->nfile.expfname;
173#ifdef O_CREAT
174		if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
175			error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
176#else
177		if ((f = creat(fname, 0666)) < 0)
178			error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
179#endif
180		goto movefd;
181	case NAPPEND:
182		fname = redir->nfile.expfname;
183#ifdef O_APPEND
184		if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
185			error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
186#else
187		if ((f = open(fname, O_WRONLY)) < 0
188		 && (f = creat(fname, 0666)) < 0)
189			error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
190		lseek(f, (off_t)0, 2);
191#endif
192		goto movefd;
193	case NTOFD:
194	case NFROMFD:
195		if (redir->ndup.dupfd >= 0) {	/* if not ">&-" */
196			if (memory[redir->ndup.dupfd])
197				memory[fd] = 1;
198			else
199				copyfd(redir->ndup.dupfd, fd);
200		}
201		break;
202	case NHERE:
203	case NXHERE:
204		f = openhere(redir);
205		goto movefd;
206	default:
207		abort();
208	}
209	INTON;
210}
211
212
213/*
214 * Handle here documents.  Normally we fork off a process to write the
215 * data to a pipe.  If the document is short, we can stuff the data in
216 * the pipe without forking.
217 */
218
219STATIC int
220openhere(redir)
221	union node *redir;
222	{
223	int pip[2];
224	int len;
225
226	if (pipe(pip) < 0)
227		error("Pipe call failed");
228	if (redir->type == NHERE) {
229		len = strlen(redir->nhere.doc->narg.text);
230		if (len <= PIPESIZE) {
231			xwrite(pip[1], redir->nhere.doc->narg.text, len);
232			goto out;
233		}
234	}
235	if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
236		close(pip[0]);
237		signal(SIGINT, SIG_IGN);
238		signal(SIGQUIT, SIG_IGN);
239		signal(SIGHUP, SIG_IGN);
240#ifdef SIGTSTP
241		signal(SIGTSTP, SIG_IGN);
242#endif
243		signal(SIGPIPE, SIG_DFL);
244		if (redir->type == NHERE)
245			xwrite(pip[1], redir->nhere.doc->narg.text, len);
246		else
247			expandhere(redir->nhere.doc, pip[1]);
248		_exit(0);
249	}
250out:
251	close(pip[1]);
252	return pip[0];
253}
254
255
256
257/*
258 * Undo the effects of the last redirection.
259 */
260
261void
262popredir() {
263	register struct redirtab *rp = redirlist;
264	int i;
265
266	for (i = 0 ; i < 10 ; i++) {
267		if (rp->renamed[i] != EMPTY) {
268                        if (i == 0)
269                                fd0_redirected--;
270			close(i);
271			if (rp->renamed[i] >= 0) {
272				copyfd(rp->renamed[i], i);
273				close(rp->renamed[i]);
274			}
275		}
276	}
277	INTOFF;
278	redirlist = rp->next;
279	ckfree(rp);
280	INTON;
281}
282
283/*
284 * Undo all redirections.  Called on error or interrupt.
285 */
286
287#ifdef mkinit
288
289INCLUDE "redir.h"
290
291RESET {
292	while (redirlist)
293		popredir();
294}
295
296SHELLPROC {
297	clearredir();
298}
299
300#endif
301
302/* Return true if fd 0 has already been redirected at least once.  */
303int
304fd0_redirected_p () {
305        return fd0_redirected != 0;
306}
307
308/*
309 * Discard all saved file descriptors.
310 */
311
312void
313clearredir() {
314	register struct redirtab *rp;
315	int i;
316
317	for (rp = redirlist ; rp ; rp = rp->next) {
318		for (i = 0 ; i < 10 ; i++) {
319			if (rp->renamed[i] >= 0) {
320				close(rp->renamed[i]);
321			}
322			rp->renamed[i] = EMPTY;
323		}
324	}
325}
326
327
328
329/*
330 * Copy a file descriptor to be >= to.  Returns -1
331 * if the source file descriptor is closed, EMPTY if there are no unused
332 * file descriptors left.
333 */
334
335int
336copyfd(from, to) {
337	int newfd;
338
339	newfd = fcntl(from, F_DUPFD, to);
340	if (newfd < 0 && errno == EMFILE)
341		return EMPTY;
342	return newfd;
343}
344