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