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