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