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