redir.c revision 96922
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
38#if 0
39static char sccsid[] = "@(#)redir.c	8.2 (Berkeley) 5/4/95";
40#endif
41static const char rcsid[] =
42  "$FreeBSD: head/bin/sh/redir.c 96922 2002-05-19 06:03:05Z tjr $";
43#endif /* not lint */
44
45#include <sys/types.h>
46#include <sys/stat.h>
47#include <signal.h>
48#include <string.h>
49#include <fcntl.h>
50#include <errno.h>
51#include <unistd.h>
52#include <stdlib.h>
53
54/*
55 * Code for dealing with input/output redirection.
56 */
57
58#include "shell.h"
59#include "nodes.h"
60#include "jobs.h"
61#include "expand.h"
62#include "redir.h"
63#include "output.h"
64#include "memalloc.h"
65#include "error.h"
66#include "options.h"
67
68
69#define EMPTY -2		/* marks an unused slot in redirtab */
70#define PIPESIZE 4096		/* amount of buffering in a pipe */
71
72
73MKINIT
74struct redirtab {
75	struct redirtab *next;
76	short renamed[10];
77};
78
79
80MKINIT struct redirtab *redirlist;
81
82/*
83 * We keep track of whether or not fd0 has been redirected.  This is for
84 * background commands, where we want to redirect fd0 to /dev/null only
85 * if it hasn't already been redirected.
86*/
87int fd0_redirected = 0;
88
89STATIC void openredirect(union node *, char[10 ]);
90STATIC int openhere(union node *);
91
92
93/*
94 * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
95 * old file descriptors are stashed away so that the redirection can be
96 * undone by calling popredir.  If the REDIR_BACKQ flag is set, then the
97 * standard output, and the standard error if it becomes a duplicate of
98 * stdout, is saved in memory.
99 */
100
101void
102redirect(union node *redir, int flags)
103{
104	union node *n;
105	struct redirtab *sv = NULL;
106	int i;
107	int fd;
108	int try;
109	char memory[10];	/* file descriptors to write to memory */
110
111	for (i = 10 ; --i >= 0 ; )
112		memory[i] = 0;
113	memory[1] = flags & REDIR_BACKQ;
114	if (flags & REDIR_PUSH) {
115		sv = ckmalloc(sizeof (struct redirtab));
116		for (i = 0 ; i < 10 ; i++)
117			sv->renamed[i] = EMPTY;
118		sv->next = redirlist;
119		redirlist = sv;
120	}
121	for (n = redir ; n ; n = n->nfile.next) {
122		fd = n->nfile.fd;
123		try = 0;
124		if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
125		    n->ndup.dupfd == fd)
126			continue; /* redirect from/to same file descriptor */
127
128		if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
129			INTOFF;
130again:
131			if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
132				switch (errno) {
133				case EBADF:
134					if (!try) {
135						openredirect(n, memory);
136						try++;
137						goto again;
138					}
139					/* FALLTHROUGH*/
140				default:
141					INTON;
142					error("%d: %s", fd, strerror(errno));
143					break;
144				}
145			}
146			if (!try) {
147				sv->renamed[fd] = i;
148			}
149			INTON;
150		}
151		if (fd == 0)
152			fd0_redirected++;
153		if (!try)
154			openredirect(n, memory);
155	}
156	if (memory[1])
157		out1 = &memout;
158	if (memory[2])
159		out2 = &memout;
160}
161
162
163STATIC void
164openredirect(union node *redir, char memory[10])
165{
166	struct stat sb;
167	int fd = redir->nfile.fd;
168	char *fname;
169	int f;
170
171	/*
172	 * We suppress interrupts so that we won't leave open file
173	 * descriptors around.  This may not be such a good idea because
174	 * an open of a device or a fifo can block indefinitely.
175	 */
176	INTOFF;
177	memory[fd] = 0;
178	switch (redir->nfile.type) {
179	case NFROM:
180		fname = redir->nfile.expfname;
181		if ((f = open(fname, O_RDONLY)) < 0)
182			error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
183movefd:
184		if (f != fd) {
185			close(fd);
186			copyfd(f, fd);
187			close(f);
188		}
189		break;
190	case NFROMTO:
191		fname = redir->nfile.expfname;
192#ifdef O_CREAT
193		if ((f = open(fname, O_RDWR|O_CREAT, 0666)) < 0)
194			error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
195#else
196		if ((f = open(fname, O_RDWR, 0666)) < 0) {
197			if (errno != ENOENT)
198				error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
199			else if ((f = creat(fname, 0666)) < 0)
200				error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
201			else {
202				close(f);
203				if ((f = open(fname, O_RDWR)) < 0) {
204					error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
205					remove(fname);
206				}
207			}
208		}
209#endif
210		goto movefd;
211	case NTO:
212		fname = redir->nfile.expfname;
213		if (Cflag && stat(fname, &sb) != -1 && S_ISREG(sb.st_mode))
214			error("cannot create %s: %s", fname,
215			    errmsg(EEXIST, E_CREAT));
216#ifdef O_CREAT
217		if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
218			error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
219#else
220		if ((f = creat(fname, 0666)) < 0)
221			error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
222#endif
223		goto movefd;
224	case NCLOBBER:
225		fname = redir->nfile.expfname;
226		if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
227			error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
228		goto movefd;
229	case NAPPEND:
230		fname = redir->nfile.expfname;
231#ifdef O_APPEND
232		if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
233			error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
234#else
235		if ((f = open(fname, O_WRONLY)) < 0
236		 && (f = creat(fname, 0666)) < 0)
237			error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
238		lseek(f, (off_t)0, 2);
239#endif
240		goto movefd;
241	case NTOFD:
242	case NFROMFD:
243		if (redir->ndup.dupfd >= 0) {	/* if not ">&-" */
244			if (memory[redir->ndup.dupfd])
245				memory[fd] = 1;
246			else {
247				close(fd);
248				copyfd(redir->ndup.dupfd, fd);
249			}
250		}
251		break;
252	case NHERE:
253	case NXHERE:
254		f = openhere(redir);
255		goto movefd;
256	default:
257		abort();
258	}
259	INTON;
260}
261
262
263/*
264 * Handle here documents.  Normally we fork off a process to write the
265 * data to a pipe.  If the document is short, we can stuff the data in
266 * the pipe without forking.
267 */
268
269STATIC int
270openhere(union node *redir)
271{
272	int pip[2];
273	int len = 0;
274
275	if (pipe(pip) < 0)
276		error("Pipe call failed: %s", strerror(errno));
277	if (redir->type == NHERE) {
278		len = strlen(redir->nhere.doc->narg.text);
279		if (len <= PIPESIZE) {
280			xwrite(pip[1], redir->nhere.doc->narg.text, len);
281			goto out;
282		}
283	}
284	if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
285		close(pip[0]);
286		signal(SIGINT, SIG_IGN);
287		signal(SIGQUIT, SIG_IGN);
288		signal(SIGHUP, SIG_IGN);
289#ifdef SIGTSTP
290		signal(SIGTSTP, SIG_IGN);
291#endif
292		signal(SIGPIPE, SIG_DFL);
293		if (redir->type == NHERE)
294			xwrite(pip[1], redir->nhere.doc->narg.text, len);
295		else
296			expandhere(redir->nhere.doc, pip[1]);
297		_exit(0);
298	}
299out:
300	close(pip[1]);
301	return pip[0];
302}
303
304
305
306/*
307 * Undo the effects of the last redirection.
308 */
309
310void
311popredir(void)
312{
313	struct redirtab *rp = redirlist;
314	int i;
315
316	for (i = 0 ; i < 10 ; i++) {
317		if (rp->renamed[i] != EMPTY) {
318                        if (i == 0)
319                                fd0_redirected--;
320			close(i);
321			if (rp->renamed[i] >= 0) {
322				copyfd(rp->renamed[i], i);
323				close(rp->renamed[i]);
324			}
325		}
326	}
327	INTOFF;
328	redirlist = rp->next;
329	ckfree(rp);
330	INTON;
331}
332
333/*
334 * Undo all redirections.  Called on error or interrupt.
335 */
336
337#ifdef mkinit
338
339INCLUDE "redir.h"
340
341RESET {
342	while (redirlist)
343		popredir();
344}
345
346SHELLPROC {
347	clearredir();
348}
349
350#endif
351
352/* Return true if fd 0 has already been redirected at least once.  */
353int
354fd0_redirected_p(void)
355{
356        return fd0_redirected != 0;
357}
358
359/*
360 * Discard all saved file descriptors.
361 */
362
363void
364clearredir(void)
365{
366	struct redirtab *rp;
367	int i;
368
369	for (rp = redirlist ; rp ; rp = rp->next) {
370		for (i = 0 ; i < 10 ; i++) {
371			if (rp->renamed[i] >= 0) {
372				close(rp->renamed[i]);
373			}
374			rp->renamed[i] = EMPTY;
375		}
376	}
377}
378
379
380
381/*
382 * Copy a file descriptor to be >= to.  Returns -1
383 * if the source file descriptor is closed, EMPTY if there are no unused
384 * file descriptors left.
385 */
386
387int
388copyfd(int from, int to)
389{
390	int newfd;
391
392	newfd = fcntl(from, F_DUPFD, to);
393	if (newfd < 0) {
394		if (errno == EMFILE)
395			return EMPTY;
396		else
397			error("%d: %s", from, strerror(errno));
398	}
399	return newfd;
400}
401