xref: /freebsd/bin/sh/redir.c (revision 70fe064ad7cab6c0444b91622f60ec6a462f308a)
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
39 static char sccsid[] = "@(#)redir.c	8.2 (Berkeley) 5/4/95";
40 #endif
41 static const char rcsid[] =
42   "$FreeBSD$";
43 #endif /* not lint */
44 
45 #include <sys/types.h>
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 "shell.h"
58 #include "nodes.h"
59 #include "jobs.h"
60 #include "expand.h"
61 #include "redir.h"
62 #include "output.h"
63 #include "memalloc.h"
64 #include "error.h"
65 
66 
67 #define EMPTY -2		/* marks an unused slot in redirtab */
68 #define PIPESIZE 4096		/* amount of buffering in a pipe */
69 
70 
71 MKINIT
72 struct redirtab {
73 	struct redirtab *next;
74 	short renamed[10];
75 };
76 
77 
78 MKINIT struct redirtab *redirlist;
79 
80 /*
81  * We keep track of whether or not fd0 has been redirected.  This is for
82  * background commands, where we want to redirect fd0 to /dev/null only
83  * if it hasn't already been redirected.
84 */
85 int fd0_redirected = 0;
86 
87 STATIC void openredirect __P((union node *, char[10 ]));
88 STATIC int openhere __P((union node *));
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 = 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;
130 again:
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 
163 STATIC void
164 openredirect(redir, memory)
165 	union node *redir;
166 	char memory[10];
167 	{
168 	int fd = redir->nfile.fd;
169 	char *fname;
170 	int f;
171 
172 	/*
173 	 * We suppress interrupts so that we won't leave open file
174 	 * descriptors around.  This may not be such a good idea because
175 	 * an open of a device or a fifo can block indefinitely.
176 	 */
177 	INTOFF;
178 	memory[fd] = 0;
179 	switch (redir->nfile.type) {
180 	case NFROM:
181 		fname = redir->nfile.expfname;
182 		if ((f = open(fname, O_RDONLY)) < 0)
183 			error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
184 movefd:
185 		if (f != fd) {
186 			close(fd);
187 			copyfd(f, fd);
188 			close(f);
189 		}
190 		break;
191 	case NFROMTO:
192 		fname = redir->nfile.expfname;
193 #ifdef O_CREAT
194 		if ((f = open(fname, O_RDWR|O_CREAT, 0666)) < 0)
195 			error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
196 #else
197 		if ((f = open(fname, O_RDWR, 0666)) < 0) {
198 			if (errno != ENOENT)
199 				error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
200 			else if ((f = creat(fname, 0666)) < 0)
201 				error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
202 			else {
203 				close(f);
204 				if ((f = open(fname, O_RDWR)) < 0) {
205 					error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
206 					remove(fname);
207 				}
208 			}
209 		}
210 #endif
211 		goto movefd;
212 	case NTO:
213 		fname = redir->nfile.expfname;
214 #ifdef O_CREAT
215 		if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
216 			error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
217 #else
218 		if ((f = creat(fname, 0666)) < 0)
219 			error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
220 #endif
221 		goto movefd;
222 	case NAPPEND:
223 		fname = redir->nfile.expfname;
224 #ifdef O_APPEND
225 		if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
226 			error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
227 #else
228 		if ((f = open(fname, O_WRONLY)) < 0
229 		 && (f = creat(fname, 0666)) < 0)
230 			error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
231 		lseek(f, (off_t)0, 2);
232 #endif
233 		goto movefd;
234 	case NTOFD:
235 	case NFROMFD:
236 		if (redir->ndup.dupfd >= 0) {	/* if not ">&-" */
237 			if (memory[redir->ndup.dupfd])
238 				memory[fd] = 1;
239 			else {
240 				close(fd);
241 				copyfd(redir->ndup.dupfd, fd);
242 			}
243 		}
244 		break;
245 	case NHERE:
246 	case NXHERE:
247 		f = openhere(redir);
248 		goto movefd;
249 	default:
250 		abort();
251 	}
252 	INTON;
253 }
254 
255 
256 /*
257  * Handle here documents.  Normally we fork off a process to write the
258  * data to a pipe.  If the document is short, we can stuff the data in
259  * the pipe without forking.
260  */
261 
262 STATIC int
263 openhere(redir)
264 	union node *redir;
265 	{
266 	int pip[2];
267 	int len = 0;
268 
269 	if (pipe(pip) < 0)
270 		error("Pipe call failed: %s", strerror(errno));
271 	if (redir->type == NHERE) {
272 		len = strlen(redir->nhere.doc->narg.text);
273 		if (len <= PIPESIZE) {
274 			xwrite(pip[1], redir->nhere.doc->narg.text, len);
275 			goto out;
276 		}
277 	}
278 	if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
279 		close(pip[0]);
280 		signal(SIGINT, SIG_IGN);
281 		signal(SIGQUIT, SIG_IGN);
282 		signal(SIGHUP, SIG_IGN);
283 #ifdef SIGTSTP
284 		signal(SIGTSTP, SIG_IGN);
285 #endif
286 		signal(SIGPIPE, SIG_DFL);
287 		if (redir->type == NHERE)
288 			xwrite(pip[1], redir->nhere.doc->narg.text, len);
289 		else
290 			expandhere(redir->nhere.doc, pip[1]);
291 		_exit(0);
292 	}
293 out:
294 	close(pip[1]);
295 	return pip[0];
296 }
297 
298 
299 
300 /*
301  * Undo the effects of the last redirection.
302  */
303 
304 void
305 popredir() {
306 	struct redirtab *rp = redirlist;
307 	int i;
308 
309 	for (i = 0 ; i < 10 ; i++) {
310 		if (rp->renamed[i] != EMPTY) {
311                         if (i == 0)
312                                 fd0_redirected--;
313 			close(i);
314 			if (rp->renamed[i] >= 0) {
315 				copyfd(rp->renamed[i], i);
316 				close(rp->renamed[i]);
317 			}
318 		}
319 	}
320 	INTOFF;
321 	redirlist = rp->next;
322 	ckfree(rp);
323 	INTON;
324 }
325 
326 /*
327  * Undo all redirections.  Called on error or interrupt.
328  */
329 
330 #ifdef mkinit
331 
332 INCLUDE "redir.h"
333 
334 RESET {
335 	while (redirlist)
336 		popredir();
337 }
338 
339 SHELLPROC {
340 	clearredir();
341 }
342 
343 #endif
344 
345 /* Return true if fd 0 has already been redirected at least once.  */
346 int
347 fd0_redirected_p () {
348         return fd0_redirected != 0;
349 }
350 
351 /*
352  * Discard all saved file descriptors.
353  */
354 
355 void
356 clearredir() {
357 	struct redirtab *rp;
358 	int i;
359 
360 	for (rp = redirlist ; rp ; rp = rp->next) {
361 		for (i = 0 ; i < 10 ; i++) {
362 			if (rp->renamed[i] >= 0) {
363 				close(rp->renamed[i]);
364 			}
365 			rp->renamed[i] = EMPTY;
366 		}
367 	}
368 }
369 
370 
371 
372 /*
373  * Copy a file descriptor to be >= to.  Returns -1
374  * if the source file descriptor is closed, EMPTY if there are no unused
375  * file descriptors left.
376  */
377 
378 int
379 copyfd(from, to)
380 	int from;
381 	int to;
382 {
383 	int newfd;
384 
385 	newfd = fcntl(from, F_DUPFD, to);
386 	if (newfd < 0) {
387 		if (errno == EMFILE)
388 			return EMPTY;
389 		else
390 			error("%d: %s", from, strerror(errno));
391 	}
392 	return newfd;
393 }
394