redir.c revision 1.47.2.2 1 /* $NetBSD: redir.c,v 1.47.2.2 2017/04/26 02:52:13 pgoyette 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.47.2.2 2017/04/26 02:52:13 pgoyette Exp $");
41 #endif
42 #endif /* not lint */
43
44 #include <sys/types.h>
45 #include <sys/param.h> /* PIPE_BUF */
46 #include <sys/stat.h>
47 #include <signal.h>
48 #include <string.h>
49 #include <fcntl.h>
50 #include <errno.h>
51 #include <unistd.h>
52 #include <stdlib.h>
53
54 /*
55 * Code for dealing with input/output redirection.
56 */
57
58 #include "main.h"
59 #include "builtins.h"
60 #include "shell.h"
61 #include "nodes.h"
62 #include "jobs.h"
63 #include "options.h"
64 #include "expand.h"
65 #include "redir.h"
66 #include "output.h"
67 #include "memalloc.h"
68 #include "mystring.h"
69 #include "error.h"
70
71
72 #define EMPTY -2 /* marks an unused slot in redirtab */
73 #define CLOSED -1 /* fd was not open before redir */
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 renamelist {
83 struct renamelist *next;
84 int orig;
85 int into;
86 };
87
88 MKINIT
89 struct redirtab {
90 struct redirtab *next;
91 struct renamelist *renamed;
92 };
93
94
95 MKINIT struct redirtab *redirlist;
96
97 /*
98 * We keep track of whether or not fd0 has been redirected. This is for
99 * background commands, where we want to redirect fd0 to /dev/null only
100 * if it hasn't already been redirected.
101 */
102 STATIC int fd0_redirected = 0;
103
104 /*
105 * And also where to put internal use fds that should be out of the
106 * way of user defined fds (normally)
107 */
108 STATIC int big_sh_fd = 0;
109
110 STATIC const struct renamelist *is_renamed(const struct renamelist *, int);
111 STATIC void fd_rename(struct redirtab *, int, int);
112 STATIC void free_rl(struct redirtab *, int);
113 STATIC void openredirect(union node *, char[10], int);
114 STATIC int openhere(const union node *);
115 STATIC int copyfd(int, int, int);
116 STATIC void find_big_fd(void);
117
118 STATIC const struct renamelist *
119 is_renamed(const struct renamelist *rl, int fd)
120 {
121 while (rl != NULL) {
122 if (rl->orig == fd)
123 return rl;
124 rl = rl->next;
125 }
126 return NULL;
127 }
128
129 STATIC void
130 free_rl(struct redirtab *rt, int reset)
131 {
132 struct renamelist *rl, *rn = rt->renamed;
133
134 while ((rl = rn) != NULL) {
135 rn = rl->next;
136 if (rl->orig == 0)
137 fd0_redirected--;
138 if (reset) {
139 if (rl->into < 0)
140 close(rl->orig);
141 else
142 movefd(rl->into, rl->orig);
143 }
144 ckfree(rl);
145 }
146 rt->renamed = NULL;
147 }
148
149 STATIC void
150 fd_rename(struct redirtab *rt, int from, int to)
151 {
152 struct renamelist *rl = ckmalloc(sizeof(struct renamelist));
153
154 rl->next = rt->renamed;
155 rt->renamed = rl;
156
157 rl->orig = from;
158 rl->into = to;
159 }
160
161 /*
162 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
163 * old file descriptors are stashed away so that the redirection can be
164 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
165 * standard output, and the standard error if it becomes a duplicate of
166 * stdout, is saved in memory.
167 */
168
169 void
170 redirect(union node *redir, int flags)
171 {
172 union node *n;
173 struct redirtab *sv = NULL;
174 int i;
175 int fd;
176 char memory[10]; /* file descriptors to write to memory */
177
178 for (i = 10 ; --i >= 0 ; )
179 memory[i] = 0;
180 memory[1] = flags & REDIR_BACKQ;
181 if (flags & REDIR_PUSH) {
182 /* We don't have to worry about REDIR_VFORK here, as
183 * flags & REDIR_PUSH is never true if REDIR_VFORK is set.
184 */
185 sv = ckmalloc(sizeof (struct redirtab));
186 sv->renamed = NULL;
187 sv->next = redirlist;
188 redirlist = sv;
189 }
190 for (n = redir ; n ; n = n->nfile.next) {
191 fd = n->nfile.fd;
192 if (fd > max_user_fd)
193 max_user_fd = fd;
194 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
195 n->ndup.dupfd == fd) {
196 /* redirect from/to same file descriptor */
197 /* make sure it stays open */
198 if (fcntl(fd, F_SETFD, 0) < 0)
199 error("fd %d: %s", fd, strerror(errno));
200 continue;
201 }
202
203 if ((flags & REDIR_PUSH) && !is_renamed(sv->renamed, fd)) {
204 INTOFF;
205 if (big_sh_fd < 10)
206 find_big_fd();
207 if ((i = fcntl(fd, F_DUPFD, big_sh_fd)) == -1) {
208 switch (errno) {
209 case EBADF:
210 i = CLOSED;
211 break;
212 case EMFILE:
213 case EINVAL:
214 find_big_fd();
215 i = fcntl(fd, F_DUPFD, big_sh_fd);
216 if (i >= 0)
217 break;
218 /* FALLTHRU */
219 default:
220 i = errno;
221 INTON; /* XXX not needed here ? */
222 error("%d: %s", fd, strerror(i));
223 /* NOTREACHED */
224 }
225 }
226 if (i >= 0)
227 (void)fcntl(i, F_SETFD, FD_CLOEXEC);
228 fd_rename(sv, fd, i);
229 INTON;
230 }
231 if (fd == 0)
232 fd0_redirected++;
233 openredirect(n, memory, flags);
234 }
235 if (memory[1])
236 out1 = &memout;
237 if (memory[2])
238 out2 = &memout;
239 }
240
241
242 STATIC void
243 openredirect(union node *redir, char memory[10], int flags)
244 {
245 struct stat sb;
246 int fd = redir->nfile.fd;
247 char *fname;
248 int f;
249 int eflags, cloexec;
250
251 /*
252 * We suppress interrupts so that we won't leave open file
253 * descriptors around. This may not be such a good idea because
254 * an open of a device or a fifo can block indefinitely.
255 */
256 INTOFF;
257 if (fd < 10)
258 memory[fd] = 0;
259 switch (redir->nfile.type) {
260 case NFROM:
261 fname = redir->nfile.expfname;
262 if (flags & REDIR_VFORK)
263 eflags = O_NONBLOCK;
264 else
265 eflags = 0;
266 if ((f = open(fname, O_RDONLY|eflags)) < 0)
267 goto eopen;
268 if (eflags)
269 (void)fcntl(f, F_SETFL, fcntl(f, F_GETFL, 0) & ~eflags);
270 break;
271 case NFROMTO:
272 fname = redir->nfile.expfname;
273 if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
274 goto ecreate;
275 break;
276 case NTO:
277 if (Cflag) {
278 fname = redir->nfile.expfname;
279 if ((f = open(fname, O_WRONLY)) == -1) {
280 if ((f = open(fname, O_WRONLY|O_CREAT|O_EXCL,
281 0666)) < 0)
282 goto ecreate;
283 } else if (fstat(f, &sb) == -1) {
284 int serrno = errno;
285 close(f);
286 errno = serrno;
287 goto ecreate;
288 } else if (S_ISREG(sb.st_mode)) {
289 close(f);
290 errno = EEXIST;
291 goto ecreate;
292 }
293 break;
294 }
295 /* FALLTHROUGH */
296 case NCLOBBER:
297 fname = redir->nfile.expfname;
298 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
299 goto ecreate;
300 break;
301 case NAPPEND:
302 fname = redir->nfile.expfname;
303 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
304 goto ecreate;
305 break;
306 case NTOFD:
307 case NFROMFD:
308 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
309 if (fd < 10 && redir->ndup.dupfd < 10 &&
310 memory[redir->ndup.dupfd])
311 memory[fd] = 1;
312 else if (copyfd(redir->ndup.dupfd, fd,
313 (flags & REDIR_KEEP) == 0) < 0)
314 error("Redirect (from %d to %d) failed: %s",
315 redir->ndup.dupfd, fd, strerror(errno));
316 } else
317 (void) close(fd);
318 INTON;
319 return;
320 case NHERE:
321 case NXHERE:
322 f = openhere(redir);
323 break;
324 default:
325 abort();
326 }
327
328 cloexec = fd > 2 && (flags & REDIR_KEEP) == 0;
329 if (f != fd) {
330 if (copyfd(f, fd, cloexec) < 0) {
331 int e = errno;
332
333 close(f);
334 error("redirect reassignment (fd %d) failed: %s", fd,
335 strerror(e));
336 }
337 close(f);
338 } else if (cloexec)
339 (void)fcntl(f, F_SETFD, FD_CLOEXEC);
340
341 INTON;
342 return;
343 ecreate:
344 exerrno = 1;
345 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
346 eopen:
347 exerrno = 1;
348 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
349 }
350
351
352 /*
353 * Handle here documents. Normally we fork off a process to write the
354 * data to a pipe. If the document is short, we can stuff the data in
355 * the pipe without forking.
356 */
357
358 STATIC int
359 openhere(const union node *redir)
360 {
361 int pip[2];
362 int len = 0;
363
364 if (pipe(pip) < 0)
365 error("Pipe call failed");
366 if (redir->type == NHERE) {
367 len = strlen(redir->nhere.doc->narg.text);
368 if (len <= PIPESIZE) {
369 xwrite(pip[1], redir->nhere.doc->narg.text, len);
370 goto out;
371 }
372 }
373 if (forkshell(NULL, NULL, FORK_NOJOB) == 0) {
374 close(pip[0]);
375 signal(SIGINT, SIG_IGN);
376 signal(SIGQUIT, SIG_IGN);
377 signal(SIGHUP, SIG_IGN);
378 #ifdef SIGTSTP
379 signal(SIGTSTP, SIG_IGN);
380 #endif
381 signal(SIGPIPE, SIG_DFL);
382 if (redir->type == NHERE)
383 xwrite(pip[1], redir->nhere.doc->narg.text, len);
384 else
385 expandhere(redir->nhere.doc, pip[1]);
386 _exit(0);
387 }
388 out:
389 close(pip[1]);
390 return pip[0];
391 }
392
393
394
395 /*
396 * Undo the effects of the last redirection.
397 */
398
399 void
400 popredir(void)
401 {
402 struct redirtab *rp = redirlist;
403
404 INTOFF;
405 free_rl(rp, 1);
406 redirlist = rp->next;
407 ckfree(rp);
408 INTON;
409 }
410
411 /*
412 * Undo all redirections. Called on error or interrupt.
413 */
414
415 #ifdef mkinit
416
417 INCLUDE "redir.h"
418
419 RESET {
420 while (redirlist)
421 popredir();
422 }
423
424 SHELLPROC {
425 clearredir(0);
426 }
427
428 #endif
429
430 /* Return true if fd 0 has already been redirected at least once. */
431 int
432 fd0_redirected_p(void)
433 {
434 return fd0_redirected != 0;
435 }
436
437 /*
438 * Discard all saved file descriptors.
439 */
440
441 void
442 clearredir(int vforked)
443 {
444 struct redirtab *rp;
445 struct renamelist *rl;
446
447 for (rp = redirlist ; rp ; rp = rp->next) {
448 if (!vforked)
449 free_rl(rp, 0);
450 else for (rl = rp->renamed; rl; rl = rl->next)
451 if (rl->into >= 0)
452 close(rl->into);
453 }
454 }
455
456
457
458 /*
459 * Copy a file descriptor to be == to.
460 * cloexec indicates if we want close-on-exec or not.
461 * Returns -1 if any error occurs.
462 */
463
464 STATIC int
465 copyfd(int from, int to, int cloexec)
466 {
467 int newfd;
468
469 if (cloexec && to > 2)
470 newfd = dup3(from, to, O_CLOEXEC);
471 else
472 newfd = dup2(from, to);
473
474 return newfd;
475 }
476
477 /*
478 * rename fd from to be fd to (closing from).
479 * close-on-exec is never set on 'to' (unless
480 * from==to and it was set on from) - ie: a no-op
481 * returns to (or errors() if an error occurs).
482 *
483 * This is mostly used for rearranging the
484 * results from pipe().
485 */
486 int
487 movefd(int from, int to)
488 {
489 if (from == to)
490 return to;
491
492 (void) close(to);
493 if (copyfd(from, to, 0) != to) {
494 int e = errno;
495
496 (void) close(from);
497 error("Unable to make fd %d: %s", to, strerror(e));
498 }
499 (void) close(from);
500
501 return to;
502 }
503
504 STATIC void
505 find_big_fd(void)
506 {
507 int i, fd;
508
509 for (i = (1 << 10); i >= 10; i >>= 1) {
510 if ((fd = fcntl(0, F_DUPFD, i - 1)) >= 0) {
511 close(fd);
512 break;
513 }
514 }
515
516 fd = (i / 5) * 4;
517 if ((i - fd) > 100)
518 fd = i - 100;
519 else if (fd < 10)
520 fd = 10;
521
522 big_sh_fd = fd;
523 }
524
525 /*
526 * If possible, move file descriptor fd out of the way
527 * of expected user fd values. Returns the new fd
528 * (which may be the input fd if things do not go well.)
529 * Always set close-on-exec on the result, and close
530 * the input fd unless it is to be our result.
531 */
532 int
533 to_upper_fd(int fd)
534 {
535 int i;
536
537 if (big_sh_fd < 10)
538 find_big_fd();
539 do {
540 i = fcntl(fd, F_DUPFD_CLOEXEC, big_sh_fd);
541 if (i >= 0) {
542 if (fd != i)
543 close(fd);
544 return i;
545 }
546 if (errno != EMFILE)
547 break;
548 find_big_fd();
549 } while (big_sh_fd > 10);
550
551 /*
552 * If we wanted to move this fd to some random high number
553 * we certainly do not intend to pass it through exec, even
554 * if the reassignment failed.
555 */
556 (void)fcntl(fd, F_SETFD, FD_CLOEXEC);
557 return fd;
558 }
559
560 static const struct flgnames {
561 const char *name;
562 uint32_t value;
563 } nv[] = {
564 #ifdef O_APPEND
565 { "append", O_APPEND },
566 #endif
567 #ifdef O_ASYNC
568 { "async", O_ASYNC },
569 #endif
570 #ifdef O_SYNC
571 { "sync", O_SYNC },
572 #endif
573 #ifdef O_NONBLOCK
574 { "nonblock", O_NONBLOCK },
575 #endif
576 #ifdef O_FSYNC
577 { "fsync", O_FSYNC },
578 #endif
579 #ifdef O_DSYNC
580 { "dsync", O_DSYNC },
581 #endif
582 #ifdef O_RSYNC
583 { "rsync", O_RSYNC },
584 #endif
585 #ifdef O_ALTIO
586 { "altio", O_ALT_IO },
587 #endif
588 #ifdef O_DIRECT
589 { "direct", O_DIRECT },
590 #endif
591 #ifdef O_NOSIGPIPE
592 { "nosigpipe", O_NOSIGPIPE },
593 #endif
594 #ifdef O_CLOEXEC
595 { "cloexec", O_CLOEXEC },
596 #endif
597 { 0, 0 }
598 };
599 #define ALLFLAGS (O_APPEND|O_ASYNC|O_SYNC|O_NONBLOCK|O_DSYNC|O_RSYNC|\
600 O_ALT_IO|O_DIRECT|O_NOSIGPIPE|O_CLOEXEC)
601
602 static int
603 getflags(int fd, int p)
604 {
605 int c, f;
606
607 if ((c = fcntl(fd, F_GETFD)) == -1) {
608 if (!p)
609 return -1;
610 error("Can't get status for fd=%d (%s)", fd, strerror(errno));
611 }
612 if ((f = fcntl(fd, F_GETFL)) == -1) {
613 if (!p)
614 return -1;
615 error("Can't get flags for fd=%d (%s)", fd, strerror(errno));
616 }
617 if (c & FD_CLOEXEC)
618 f |= O_CLOEXEC;
619 return f & ALLFLAGS;
620 }
621
622 static void
623 printone(int fd, int p, int verbose, int pfd)
624 {
625 int f = getflags(fd, p);
626 const struct flgnames *fn;
627
628 if (f == -1)
629 return;
630
631 if (pfd)
632 outfmt(out1, "%d: ", fd);
633 for (fn = nv; fn->name; fn++) {
634 if (f & fn->value) {
635 outfmt(out1, "%s%s", verbose ? "+" : "", fn->name);
636 f &= ~fn->value;
637 } else if (verbose)
638 outfmt(out1, "-%s", fn->name);
639 else
640 continue;
641 if (f || (verbose && fn[1].name))
642 outfmt(out1, ",");
643 }
644 if (verbose && f) /* f should be normally be 0 */
645 outfmt(out1, " +%#x", f);
646 outfmt(out1, "\n");
647 }
648
649 static void
650 parseflags(char *s, int *p, int *n)
651 {
652 int *v, *w;
653 const struct flgnames *fn;
654
655 *p = 0;
656 *n = 0;
657 for (s = strtok(s, ","); s; s = strtok(NULL, ",")) {
658 switch (*s++) {
659 case '+':
660 v = p;
661 w = n;
662 break;
663 case '-':
664 v = n;
665 w = p;
666 break;
667 default:
668 error("Missing +/- indicator before flag %s", s-1);
669 }
670
671 for (fn = nv; fn->name; fn++)
672 if (strcmp(s, fn->name) == 0) {
673 *v |= fn->value;
674 *w &=~ fn->value;
675 break;
676 }
677 if (fn->name == 0)
678 error("Bad flag `%s'", s);
679 }
680 }
681
682 static void
683 setone(int fd, int pos, int neg, int verbose)
684 {
685 int f = getflags(fd, 1);
686 int n, cloexec;
687
688 if (f == -1)
689 return;
690
691 cloexec = -1;
692 if ((pos & O_CLOEXEC) && !(f & O_CLOEXEC))
693 cloexec = FD_CLOEXEC;
694 if ((neg & O_CLOEXEC) && (f & O_CLOEXEC))
695 cloexec = 0;
696
697 if (cloexec != -1 && fcntl(fd, F_SETFD, cloexec) == -1)
698 error("Can't set status for fd=%d (%s)", fd, strerror(errno));
699
700 pos &= ~O_CLOEXEC;
701 neg &= ~O_CLOEXEC;
702 f &= ~O_CLOEXEC;
703 n = f;
704 n |= pos;
705 n &= ~neg;
706 if (n != f && fcntl(fd, F_SETFL, n) == -1)
707 error("Can't set flags for fd=%d (%s)", fd, strerror(errno));
708 if (verbose)
709 printone(fd, 1, verbose, 1);
710 }
711
712 int
713 fdflagscmd(int argc, char *argv[])
714 {
715 char *num;
716 int verbose = 0, ch, pos = 0, neg = 0;
717 char *setflags = NULL;
718
719 optreset = 1; optind = 1; /* initialize getopt */
720 while ((ch = getopt(argc, argv, ":vs:")) != -1)
721 switch ((char)ch) {
722 case 'v':
723 verbose = 1;
724 break;
725 case 's':
726 if (setflags)
727 goto msg;
728 setflags = optarg;
729 break;
730 case '?':
731 default:
732 msg:
733 error("Usage: fdflags [-v] [-s <flags> fd] [fd...]");
734 /* NOTREACHED */
735 }
736
737 argc -= optind, argv += optind;
738
739 if (setflags)
740 parseflags(setflags, &pos, &neg);
741
742 if (argc == 0) {
743 int i;
744
745 if (setflags)
746 goto msg;
747
748 /*
749 * XXX we should only ever operate on user defined fds
750 * XXX not on sh internal fds that might be open.
751 * XXX but for that we need to know their range (later)
752 */
753 for (i = 0; i <= max_user_fd; i++)
754 printone(i, 0, verbose, 1);
755 return 0;
756 }
757
758 while ((num = *argv++) != NULL) {
759 int fd = number(num);
760
761 while (num[0] == '0' && num[1] != '\0') /* skip 0's */
762 num++;
763 if (strlen(num) > 5)
764 error("%s too big to be a file descriptor", num);
765
766 if (setflags)
767 setone(fd, pos, neg, verbose);
768 else
769 printone(fd, 1, verbose, argc > 1);
770 }
771 return 0;
772 }
773