redir.c revision 1.43 1 /* $NetBSD: redir.c,v 1.43 2016/05/02 01:46:31 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. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35 #include <sys/cdefs.h>
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)redir.c 8.2 (Berkeley) 5/4/95";
39 #else
40 __RCSID("$NetBSD: redir.c,v 1.43 2016/05/02 01:46:31 christos Exp $");
41 #endif
42 #endif /* not lint */
43
44 #include <sys/types.h>
45 #include <sys/param.h> /* PIPE_BUF */
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 "main.h"
58 #include "shell.h"
59 #include "nodes.h"
60 #include "jobs.h"
61 #include "options.h"
62 #include "expand.h"
63 #include "redir.h"
64 #include "output.h"
65 #include "memalloc.h"
66 #include "error.h"
67
68
69 #define EMPTY -2 /* marks an unused slot in redirtab */
70 #define CLOSED -1 /* fd was not open before redir */
71 #ifndef PIPE_BUF
72 # define PIPESIZE 4096 /* amount of buffering in a pipe */
73 #else
74 # define PIPESIZE PIPE_BUF
75 #endif
76
77
78 MKINIT
79 struct renamelist {
80 struct renamelist *next;
81 int orig;
82 int into;
83 };
84
85 MKINIT
86 struct redirtab {
87 struct redirtab *next;
88 struct renamelist *renamed;
89 };
90
91
92 MKINIT struct redirtab *redirlist;
93
94 /*
95 * We keep track of whether or not fd0 has been redirected. This is for
96 * background commands, where we want to redirect fd0 to /dev/null only
97 * if it hasn't already been redirected.
98 */
99 STATIC int fd0_redirected = 0;
100
101 /*
102 * And also where to put internal use fds that should be out of the
103 * way of user defined fds (normally)
104 */
105 STATIC int big_sh_fd = 0;
106
107 STATIC const struct renamelist *is_renamed(const struct renamelist *, int);
108 STATIC void fd_rename(struct redirtab *, int, int);
109 STATIC void free_rl(struct redirtab *, int);
110 STATIC void openredirect(union node *, char[10], int);
111 STATIC int openhere(const union node *);
112 STATIC void find_big_fd(void);
113
114 STATIC const struct renamelist *
115 is_renamed(const struct renamelist *rl, int fd)
116 {
117 while (rl != NULL) {
118 if (rl->orig == fd)
119 return rl;
120 rl = rl->next;
121 }
122 return NULL;
123 }
124
125 STATIC void
126 free_rl(struct redirtab *rt, int reset)
127 {
128 struct renamelist *rl, *rn = rt->renamed;
129
130 while ((rl = rn) != NULL) {
131 rn = rl->next;
132 if (rl->orig == 0)
133 fd0_redirected--;
134 if (reset) {
135 if (rl->into < 0)
136 close(rl->orig);
137 else
138 movefd(rl->into, rl->orig);
139 }
140 ckfree(rl);
141 }
142 rt->renamed = NULL;
143 }
144
145 STATIC void
146 fd_rename(struct redirtab *rt, int from, int to)
147 {
148 struct renamelist *rl = ckmalloc(sizeof(struct renamelist));
149
150 rl->next = rt->renamed;
151 rt->renamed = rl;
152
153 rl->orig = from;
154 rl->into = to;
155 }
156
157 /*
158 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
159 * old file descriptors are stashed away so that the redirection can be
160 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
161 * standard output, and the standard error if it becomes a duplicate of
162 * stdout, is saved in memory.
163 */
164
165 void
166 redirect(union node *redir, int flags)
167 {
168 union node *n;
169 struct redirtab *sv = NULL;
170 int i;
171 int fd;
172 char memory[10]; /* file descriptors to write to memory */
173
174 for (i = 10 ; --i >= 0 ; )
175 memory[i] = 0;
176 memory[1] = flags & REDIR_BACKQ;
177 if (flags & REDIR_PUSH) {
178 /* We don't have to worry about REDIR_VFORK here, as
179 * flags & REDIR_PUSH is never true if REDIR_VFORK is set.
180 */
181 sv = ckmalloc(sizeof (struct redirtab));
182 sv->renamed = NULL;
183 sv->next = redirlist;
184 redirlist = sv;
185 }
186 for (n = redir ; n ; n = n->nfile.next) {
187 fd = n->nfile.fd;
188 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
189 n->ndup.dupfd == fd) {
190 /* redirect from/to same file descriptor */
191 fcntl(fd, F_SETFD, 0); /* make sure it stays open */
192 continue;
193 }
194
195 if ((flags & REDIR_PUSH) && !is_renamed(sv->renamed, fd)) {
196 INTOFF;
197 if (big_sh_fd < 10)
198 find_big_fd();
199 if ((i = fcntl(fd, F_DUPFD, big_sh_fd)) == -1) {
200 switch (errno) {
201 case EBADF:
202 i = CLOSED;
203 break;
204 case EMFILE:
205 case EINVAL:
206 find_big_fd();
207 i = fcntl(fd, F_DUPFD, big_sh_fd);
208 if (i >= 0)
209 break;
210 /* FALLTHRU */
211 default:
212 i = errno;
213 INTON; /* XXX not needed here ? */
214 error("%d: %s", fd, strerror(i));
215 /* NOTREACHED */
216 }
217 }
218 if (i >= 0)
219 (void)fcntl(i, F_SETFD, FD_CLOEXEC);
220 fd_rename(sv, fd, i);
221 INTON;
222 } else {
223 close(fd);
224 }
225 if (fd == 0)
226 fd0_redirected++;
227 openredirect(n, memory, flags);
228 }
229 if (memory[1])
230 out1 = &memout;
231 if (memory[2])
232 out2 = &memout;
233 }
234
235
236 STATIC void
237 openredirect(union node *redir, char memory[10], int flags)
238 {
239 struct stat sb;
240 int fd = redir->nfile.fd;
241 char *fname;
242 int f;
243 int eflags, cloexec;
244
245 /*
246 * We suppress interrupts so that we won't leave open file
247 * descriptors around. This may not be such a good idea because
248 * an open of a device or a fifo can block indefinitely.
249 */
250 INTOFF;
251 if (fd < 10)
252 memory[fd] = 0;
253 switch (redir->nfile.type) {
254 case NFROM:
255 fname = redir->nfile.expfname;
256 if (flags & REDIR_VFORK)
257 eflags = O_NONBLOCK;
258 else
259 eflags = 0;
260 if ((f = open(fname, O_RDONLY|eflags)) < 0)
261 goto eopen;
262 if (eflags)
263 (void)fcntl(f, F_SETFL, fcntl(f, F_GETFL, 0) & ~eflags);
264 break;
265 case NFROMTO:
266 fname = redir->nfile.expfname;
267 if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
268 goto ecreate;
269 break;
270 case NTO:
271 if (Cflag) {
272 fname = redir->nfile.expfname;
273 if ((f = open(fname, O_WRONLY)) == -1) {
274 if ((f = open(fname, O_WRONLY|O_CREAT|O_EXCL,
275 0666)) < 0)
276 goto ecreate;
277 } else if (fstat(f, &sb) == -1) {
278 int serrno = errno;
279 close(f);
280 errno = serrno;
281 goto ecreate;
282 } else if (S_ISREG(sb.st_mode)) {
283 close(f);
284 errno = EEXIST;
285 goto ecreate;
286 }
287 break;
288 }
289 /* FALLTHROUGH */
290 case NCLOBBER:
291 fname = redir->nfile.expfname;
292 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
293 goto ecreate;
294 break;
295 case NAPPEND:
296 fname = redir->nfile.expfname;
297 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
298 goto ecreate;
299 break;
300 case NTOFD:
301 case NFROMFD:
302 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
303 if (fd < 10 && redir->ndup.dupfd < 10 &&
304 memory[redir->ndup.dupfd])
305 memory[fd] = 1;
306 else
307 copyfd(redir->ndup.dupfd, fd, 1,
308 (flags & REDIR_PUSH) != 0);
309 }
310 INTON;
311 return;
312 case NHERE:
313 case NXHERE:
314 f = openhere(redir);
315 break;
316 default:
317 abort();
318 }
319
320 cloexec = fd > 2 && (flags & REDIR_KEEP) == 0;
321 if (f != fd) {
322 copyfd(f, fd, 1, cloexec);
323 close(f);
324 } else if (cloexec)
325 (void)fcntl(f, F_SETFD, FD_CLOEXEC);
326
327 INTON;
328 return;
329 ecreate:
330 exerrno = 1;
331 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
332 eopen:
333 exerrno = 1;
334 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
335 }
336
337
338 /*
339 * Handle here documents. Normally we fork off a process to write the
340 * data to a pipe. If the document is short, we can stuff the data in
341 * the pipe without forking.
342 */
343
344 STATIC int
345 openhere(const union node *redir)
346 {
347 int pip[2];
348 int len = 0;
349
350 if (pipe(pip) < 0)
351 error("Pipe call failed");
352 if (redir->type == NHERE) {
353 len = strlen(redir->nhere.doc->narg.text);
354 if (len <= PIPESIZE) {
355 xwrite(pip[1], redir->nhere.doc->narg.text, len);
356 goto out;
357 }
358 }
359 if (forkshell(NULL, NULL, FORK_NOJOB) == 0) {
360 close(pip[0]);
361 signal(SIGINT, SIG_IGN);
362 signal(SIGQUIT, SIG_IGN);
363 signal(SIGHUP, SIG_IGN);
364 #ifdef SIGTSTP
365 signal(SIGTSTP, SIG_IGN);
366 #endif
367 signal(SIGPIPE, SIG_DFL);
368 if (redir->type == NHERE)
369 xwrite(pip[1], redir->nhere.doc->narg.text, len);
370 else
371 expandhere(redir->nhere.doc, pip[1]);
372 _exit(0);
373 }
374 out:
375 close(pip[1]);
376 return pip[0];
377 }
378
379
380
381 /*
382 * Undo the effects of the last redirection.
383 */
384
385 void
386 popredir(void)
387 {
388 struct redirtab *rp = redirlist;
389
390 INTOFF;
391 free_rl(rp, 1);
392 redirlist = rp->next;
393 ckfree(rp);
394 INTON;
395 }
396
397 /*
398 * Undo all redirections. Called on error or interrupt.
399 */
400
401 #ifdef mkinit
402
403 INCLUDE "redir.h"
404
405 RESET {
406 while (redirlist)
407 popredir();
408 }
409
410 SHELLPROC {
411 clearredir(0);
412 }
413
414 #endif
415
416 /* Return true if fd 0 has already been redirected at least once. */
417 int
418 fd0_redirected_p(void)
419 {
420 return fd0_redirected != 0;
421 }
422
423 /*
424 * Discard all saved file descriptors.
425 */
426
427 void
428 clearredir(int vforked)
429 {
430 struct redirtab *rp;
431 struct renamelist *rl;
432
433 for (rp = redirlist ; rp ; rp = rp->next) {
434 if (!vforked)
435 free_rl(rp, 0);
436 else for (rl = rp->renamed; rl; rl = rl->next)
437 if (rl->into >= 0)
438 close(rl->into);
439 }
440 }
441
442
443
444 /*
445 * Copy a file descriptor to be >= to. Returns -1
446 * if the source file descriptor is closed, EMPTY if there are no unused
447 * file descriptors left.
448 */
449
450 int
451 copyfd(int from, int to, int equal, int cloexec)
452 {
453 int newfd;
454
455 if (cloexec && to > 2) {
456 if (equal)
457 newfd = dup3(from, to, O_CLOEXEC);
458 else
459 newfd = fcntl(from, F_DUPFD_CLOEXEC, to);
460 } else {
461 if (equal)
462 newfd = dup2(from, to);
463 else
464 newfd = fcntl(from, F_DUPFD, to);
465 }
466 if (newfd < 0) {
467 if (errno == EMFILE)
468 return EMPTY;
469 else
470 error("%d: %s", from, strerror(errno));
471 }
472 return newfd;
473 }
474
475 int
476 movefd(int from, int to)
477 {
478 if (from == to)
479 return to;
480
481 (void) close(to);
482 if (copyfd(from, to, 1, 0) != to)
483 error("Unable to make fd %d", to);
484 (void) close(from);
485
486 return to;
487 }
488
489 STATIC void
490 find_big_fd(void)
491 {
492 int i, fd;
493
494 for (i = (1 << 10); i >= 10; i >>= 1) {
495 if ((fd = fcntl(0, F_DUPFD, i - 1)) >= 0) {
496 close(fd);
497 break;
498 }
499 }
500
501 fd = (i / 5) * 4;
502 if ((i - fd) > 100)
503 fd = i - 100;
504 else if (fd < 10)
505 fd = 10;
506
507 big_sh_fd = fd;
508 }
509
510 int
511 to_upper_fd(int fd)
512 {
513 int i;
514
515 if (big_sh_fd < 10)
516 find_big_fd();
517 do {
518 i = fcntl(fd, F_DUPFD, big_sh_fd);
519 if (i >= 0) {
520 if (fd != i)
521 close(fd);
522 return i;
523 }
524 if (errno != EMFILE)
525 break;
526 find_big_fd();
527 } while (big_sh_fd > 10);
528
529 return fd;
530 }
531