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