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