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