redir.c revision 1.68 1 /* $NetBSD: redir.c,v 1.68 2021/09/15 18:29:45 kre 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.68 2021/09/15 18:29:45 kre 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 #include "show.h"
71
72
73 #define EMPTY -2 /* marks an unused slot in redirtab */
74 #define CLOSED -1 /* fd was not open before redir */
75 #ifndef PIPE_BUF
76 # define PIPESIZE 4096 /* amount of buffering in a pipe */
77 #else
78 # define PIPESIZE PIPE_BUF
79 #endif
80
81 #ifndef FD_CLOEXEC
82 # define FD_CLOEXEC 1 /* well known from before there was a name */
83 #endif
84
85 #ifndef F_DUPFD_CLOEXEC
86 #define F_DUPFD_CLOEXEC F_DUPFD
87 #define CLOEXEC(fd) (fcntl((fd), F_SETFD, fcntl((fd),F_GETFD) | FD_CLOEXEC))
88 #else
89 #define CLOEXEC(fd)
90 #endif
91
92
93 MKINIT
94 struct renamelist {
95 struct renamelist *next;
96 int orig;
97 int into;
98 };
99
100 MKINIT
101 struct redirtab {
102 struct redirtab *next;
103 struct renamelist *renamed;
104 };
105
106
107 MKINIT struct redirtab *redirlist;
108
109 /*
110 * We keep track of whether or not fd0 has been redirected. This is for
111 * background commands, where we want to redirect fd0 to /dev/null only
112 * if it hasn't already been redirected.
113 */
114 STATIC int fd0_redirected = 0;
115
116 /*
117 * And also where to put internal use fds that should be out of the
118 * way of user defined fds (normally)
119 */
120 STATIC int big_sh_fd = 0;
121
122 STATIC const struct renamelist *is_renamed(const struct renamelist *, int);
123 STATIC void fd_rename(struct redirtab *, int, int);
124 STATIC int * saved_redirected_fd(int);
125 STATIC void free_rl(struct redirtab *, int);
126 STATIC void openredirect(union node *, char[10], int);
127 STATIC int openhere(const union node *);
128 STATIC int copyfd(int, int, int);
129 STATIC void find_big_fd(void);
130
131
132 struct shell_fds { /* keep track of internal shell fds */
133 struct shell_fds *nxt;
134 void (*cb)(int, int);
135 int fd;
136 };
137
138 STATIC struct shell_fds *sh_fd_list;
139
140 STATIC int pick_new_fd(int);
141 STATIC void renumber_sh_fd(struct shell_fds *);
142 STATIC struct shell_fds *sh_fd(int);
143
144 STATIC const struct renamelist *
145 is_renamed(const struct renamelist *rl, int fd)
146 {
147 while (rl != NULL) {
148 if (rl->orig == fd)
149 return rl;
150 rl = rl->next;
151 }
152 return NULL;
153 }
154
155 STATIC int *
156 saved_redirected_fd(int fd)
157 {
158 struct redirtab *rt;
159 struct renamelist *rl;
160
161 for (rt = redirlist; rt != NULL; rt = rt->next) {
162 for (rl = rt->renamed; rl != NULL; rl = rl->next) {
163 if (rl->into == fd)
164 return &rl->into;
165 }
166 }
167 return NULL;
168 }
169
170 STATIC void
171 free_rl(struct redirtab *rt, int reset)
172 {
173 struct renamelist *rl, *rn = rt->renamed;
174
175 while ((rl = rn) != NULL) {
176 rn = rl->next;
177 if (rl->orig == 0)
178 fd0_redirected--;
179 VTRACE(DBG_REDIR, ("popredir %d%s: %s",
180 rl->orig, rl->orig==0 ? " (STDIN)" : "",
181 reset ? "" : "no reset\n"));
182 if (reset) {
183 if (rl->into < 0) {
184 VTRACE(DBG_REDIR, ("closed\n"));
185 close(rl->orig);
186 } else {
187 VTRACE(DBG_REDIR, ("from %d\n", rl->into));
188 movefd(rl->into, rl->orig);
189 }
190 }
191 ckfree(rl);
192 }
193 rt->renamed = NULL;
194 }
195
196 STATIC void
197 fd_rename(struct redirtab *rt, int from, int to)
198 {
199 /* XXX someday keep a short list (8..10) of freed renamelists XXX */
200 struct renamelist *rl = ckmalloc(sizeof(struct renamelist));
201
202 rl->next = rt->renamed;
203 rt->renamed = rl;
204
205 rl->orig = from;
206 rl->into = to;
207 }
208
209 /*
210 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
211 * old file descriptors are stashed away so that the redirection can be
212 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
213 * standard output, and the standard error if it becomes a duplicate of
214 * stdout, is saved in memory.
215 */
216
217 void
218 redirect(union node *redir, int flags)
219 {
220 union node *n;
221 struct redirtab *sv = NULL;
222 int i;
223 int fd;
224 char memory[10]; /* file descriptors to write to memory */
225
226 CTRACE(DBG_REDIR, ("redirect(F=0x%x):%s\n", flags, redir?"":" NONE"));
227 for (i = 10 ; --i >= 0 ; )
228 memory[i] = 0;
229 memory[1] = flags & REDIR_BACKQ;
230 if (flags & REDIR_PUSH) {
231 /*
232 * We don't have to worry about REDIR_VFORK here, as
233 * flags & REDIR_PUSH is never true if REDIR_VFORK is set.
234 */
235 sv = ckmalloc(sizeof (struct redirtab));
236 sv->renamed = NULL;
237 sv->next = redirlist;
238 redirlist = sv;
239 }
240 for (n = redir ; n ; n = n->nfile.next) {
241 int *renamed;
242
243 fd = n->nfile.fd;
244 VTRACE(DBG_REDIR, ("redir %d (max=%d limit=%ld) ",
245 fd, max_user_fd, user_fd_limit));
246 if (fd < user_fd_limit && fd > max_user_fd)
247 max_user_fd = fd;
248 if ((renamed = saved_redirected_fd(fd)) != NULL) {
249 int to = pick_new_fd(fd);
250
251 VTRACE(DBG_REDIR,
252 ("redirect: moved holding fd %d to %d\n", fd, to));
253 *renamed = to;
254 if (to != fd) /* always... */
255 (void)close(fd);
256 }
257 renumber_sh_fd(sh_fd(fd));
258 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
259 n->ndup.dupfd == fd) {
260 /* redirect from/to same file descriptor */
261 /* make sure it stays open */
262 if (fcntl(fd, F_SETFD, 0) < 0)
263 error("fd %d: %s", fd, strerror(errno));
264 VTRACE(DBG_REDIR, ("!cloexec\n"));
265 continue;
266 }
267
268 if ((flags & REDIR_PUSH) && !is_renamed(sv->renamed, fd)) {
269 int bigfd;
270
271 INTOFF;
272 if (big_sh_fd < 10)
273 find_big_fd();
274 if ((bigfd = big_sh_fd) < max_user_fd)
275 bigfd = max_user_fd;
276 if ((i = fcntl(fd, F_DUPFD, bigfd + 1)) == -1) {
277 switch (errno) {
278 case EBADF:
279 i = CLOSED;
280 break;
281 case EMFILE:
282 case EINVAL:
283 find_big_fd();
284 i = fcntl(fd, F_DUPFD, big_sh_fd);
285 if (i >= 0)
286 break;
287 if (errno == EMFILE || errno == EINVAL)
288 i = fcntl(fd, F_DUPFD, 3);
289 if (i >= 0)
290 break;
291 /* FALLTHRU */
292 default:
293 error("%d: %s", fd, strerror(errno));
294 /* NOTREACHED */
295 }
296 }
297 if (i >= 0)
298 (void)fcntl(i, F_SETFD, FD_CLOEXEC);
299 fd_rename(sv, fd, i);
300 VTRACE(DBG_REDIR, ("fd %d saved as %d ", fd, i));
301 INTON;
302 }
303 VTRACE(DBG_REDIR, ("%s\n", fd == 0 ? "STDIN" : ""));
304 if (fd == 0)
305 fd0_redirected++;
306 openredirect(n, memory, flags);
307 }
308 if (memory[1])
309 out1 = &memout;
310 if (memory[2])
311 out2 = &memout;
312 }
313
314
315 STATIC void
316 openredirect(union node *redir, char memory[10], int flags)
317 {
318 struct stat sb;
319 int fd = redir->nfile.fd;
320 char *fname;
321 int f;
322 int eflags, cloexec;
323
324 /*
325 * We suppress interrupts so that we won't leave open file
326 * descriptors around. This may not be such a good idea because
327 * an open of a device or a fifo can block indefinitely.
328 */
329 INTOFF;
330 if (fd < 10)
331 memory[fd] = 0;
332 switch (redir->nfile.type) {
333 case NFROM:
334 fname = redir->nfile.expfname;
335 if (flags & REDIR_VFORK)
336 eflags = O_NONBLOCK;
337 else
338 eflags = 0;
339 if ((f = open(fname, O_RDONLY|eflags)) < 0)
340 goto eopen;
341 VTRACE(DBG_REDIR, ("openredirect(< '%s') -> %d [%#x]",
342 fname, f, eflags));
343 if (eflags)
344 (void)fcntl(f, F_SETFL, fcntl(f, F_GETFL, 0) & ~eflags);
345 break;
346 case NFROMTO:
347 fname = redir->nfile.expfname;
348 if ((f = open(fname, O_RDWR|O_CREAT, 0666)) < 0)
349 goto ecreate;
350 VTRACE(DBG_REDIR, ("openredirect(<> '%s') -> %d", fname, f));
351 break;
352 case NTO:
353 if (Cflag) {
354 fname = redir->nfile.expfname;
355 if ((f = open(fname, O_WRONLY)) == -1) {
356 if ((f = open(fname, O_WRONLY|O_CREAT|O_EXCL,
357 0666)) < 0)
358 goto ecreate;
359 } else if (fstat(f, &sb) == -1) {
360 int serrno = errno;
361 close(f);
362 errno = serrno;
363 goto ecreate;
364 } else if (S_ISREG(sb.st_mode)) {
365 close(f);
366 errno = EEXIST;
367 goto ecreate;
368 }
369 VTRACE(DBG_REDIR, ("openredirect(>| '%s') -> %d",
370 fname, f));
371 break;
372 }
373 /* FALLTHROUGH */
374 case NCLOBBER:
375 fname = redir->nfile.expfname;
376 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
377 goto ecreate;
378 VTRACE(DBG_REDIR, ("openredirect(> '%s') -> %d", fname, f));
379 break;
380 case NAPPEND:
381 fname = redir->nfile.expfname;
382 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
383 goto ecreate;
384 VTRACE(DBG_REDIR, ("openredirect(>> '%s') -> %d", fname, f));
385 break;
386 case NTOFD:
387 case NFROMFD:
388 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
389 if (sh_fd(redir->ndup.dupfd) != NULL ||
390 saved_redirected_fd(redir->ndup.dupfd) != NULL)
391 error("Redirect (from %d to %d) failed: %s",
392 redir->ndup.dupfd, fd, strerror(EBADF));
393 if (fd < 10 && redir->ndup.dupfd < 10 &&
394 memory[redir->ndup.dupfd])
395 memory[fd] = 1;
396 else if (copyfd(redir->ndup.dupfd, fd,
397 (flags & REDIR_KEEP) == 0) < 0)
398 error("Redirect (from %d to %d) failed: %s",
399 redir->ndup.dupfd, fd, strerror(errno));
400 VTRACE(DBG_REDIR, ("openredirect: %d%c&%d\n", fd,
401 "<>"[redir->nfile.type==NTOFD], redir->ndup.dupfd));
402 } else {
403 (void) close(fd);
404 VTRACE(DBG_REDIR, ("openredirect: %d%c&-\n", fd,
405 "<>"[redir->nfile.type==NTOFD]));
406 }
407 INTON;
408 return;
409 case NHERE:
410 case NXHERE:
411 VTRACE(DBG_REDIR, ("openredirect: %d<<...", fd));
412 f = openhere(redir);
413 break;
414 default:
415 abort();
416 }
417
418 cloexec = fd > 2 && (flags & REDIR_KEEP) == 0 && !posix;
419 if (f != fd) {
420 VTRACE(DBG_REDIR, (" -> %d", fd));
421 if (copyfd(f, fd, cloexec) < 0) {
422 int e = errno;
423
424 close(f);
425 error("redirect reassignment (fd %d) failed: %s", fd,
426 strerror(e));
427 }
428 close(f);
429 } else if (cloexec)
430 (void)fcntl(f, F_SETFD, FD_CLOEXEC);
431 VTRACE(DBG_REDIR, ("%s\n", cloexec ? " cloexec" : ""));
432
433 INTON;
434 return;
435 ecreate:
436 exerrno = 1;
437 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
438 eopen:
439 exerrno = 1;
440 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
441 }
442
443
444 /*
445 * Handle here documents. Normally we fork off a process to write the
446 * data to a pipe. If the document is short, we can stuff the data in
447 * the pipe without forking.
448 */
449
450 STATIC int
451 openhere(const union node *redir)
452 {
453 int pip[2];
454 int len = 0;
455
456 if (pipe(pip) < 0)
457 error("Pipe call failed");
458 if (redir->type == NHERE) {
459 len = strlen(redir->nhere.doc->narg.text);
460 if (len <= PIPESIZE) {
461 xwrite(pip[1], redir->nhere.doc->narg.text, len);
462 goto out;
463 }
464 }
465 VTRACE(DBG_REDIR, (" forking [%d,%d]\n", pip[0], pip[1]));
466 if (forkshell(NULL, NULL, FORK_NOJOB) == 0) {
467 close(pip[0]);
468 signal(SIGINT, SIG_IGN);
469 signal(SIGQUIT, SIG_IGN);
470 signal(SIGHUP, SIG_IGN);
471 #ifdef SIGTSTP
472 signal(SIGTSTP, SIG_IGN);
473 #endif
474 signal(SIGPIPE, SIG_DFL);
475 if (redir->type == NHERE)
476 xwrite(pip[1], redir->nhere.doc->narg.text, len);
477 else
478 expandhere(redir->nhere.doc, pip[1]);
479 VTRACE(DBG_PROCS|DBG_REDIR, ("wrote here doc. exiting\n"));
480 _exit(0);
481 }
482 VTRACE(DBG_REDIR, ("openhere (closing %d)", pip[1]));
483 out:
484 close(pip[1]);
485 VTRACE(DBG_REDIR, (" (pipe fd=%d)", pip[0]));
486 return pip[0];
487 }
488
489
490
491 /*
492 * Undo the effects of the last redirection.
493 */
494
495 void
496 popredir(void)
497 {
498 struct redirtab *rp = redirlist;
499
500 INTOFF;
501 free_rl(rp, 1);
502 redirlist = rp->next;
503 ckfree(rp);
504 INTON;
505 }
506
507 /*
508 * Undo all redirections. Called on error or interrupt.
509 */
510
511 #ifdef mkinit
512
513 INCLUDE "redir.h"
514
515 RESET {
516 while (redirlist)
517 popredir();
518 }
519
520 SHELLPROC {
521 clearredir(0);
522 }
523
524 #endif
525
526 /* Return true if fd 0 has already been redirected at least once. */
527 int
528 fd0_redirected_p(void)
529 {
530 return fd0_redirected != 0;
531 }
532
533 /*
534 * Discard all saved file descriptors.
535 */
536
537 void
538 clearredir(int vforked)
539 {
540 struct redirtab *rp;
541 struct renamelist *rl;
542
543 for (rp = redirlist ; rp ; rp = rp->next) {
544 if (!vforked)
545 free_rl(rp, 0);
546 else for (rl = rp->renamed; rl; rl = rl->next)
547 if (rl->into >= 0)
548 close(rl->into);
549 }
550 }
551
552
553
554 /*
555 * Copy a file descriptor to be == to.
556 * cloexec indicates if we want close-on-exec or not.
557 * Returns -1 if any error occurs.
558 */
559
560 STATIC int
561 copyfd(int from, int to, int cloexec)
562 {
563 int newfd;
564
565 if (cloexec && to > 2) {
566 #ifdef O_CLOEXEC
567 newfd = dup3(from, to, O_CLOEXEC);
568 #else
569 newfd = dup2(from, to);
570 fcntl(newfd, F_SETFD, fcntl(newfd,F_GETFD) | FD_CLOEXEC);
571 #endif
572 } else
573 newfd = dup2(from, to);
574
575 return newfd;
576 }
577
578 /*
579 * rename fd from to be fd to (closing from).
580 * close-on-exec is never set on 'to' (unless
581 * from==to and it was set on from) - ie: a no-op
582 * returns to (or errors() if an error occurs).
583 *
584 * This is mostly used for rearranging the
585 * results from pipe().
586 */
587 int
588 movefd(int from, int to)
589 {
590 if (from == to)
591 return to;
592
593 (void) close(to);
594 if (copyfd(from, to, 0) != to) {
595 int e = errno;
596
597 (void) close(from);
598 error("Unable to make fd %d: %s", to, strerror(e));
599 }
600 (void) close(from);
601
602 return to;
603 }
604
605 STATIC void
606 find_big_fd(void)
607 {
608 int i, fd;
609 static int last_start = 3; /* aim to keep sh fd's under 20 */
610
611 if (last_start < 10)
612 last_start++;
613
614 for (i = (1 << last_start); i >= 10; i >>= 1) {
615 if ((fd = fcntl(0, F_DUPFD, i - 1)) >= 0) {
616 close(fd);
617 break;
618 }
619 }
620
621 fd = (i / 5) * 4;
622 if (fd < 10)
623 fd = 10;
624
625 big_sh_fd = fd;
626 }
627
628 /*
629 * If possible, move file descriptor fd out of the way
630 * of expected user fd values. Returns the new fd
631 * (which may be the input fd if things do not go well.)
632 * Always set close-on-exec on the result, and close
633 * the input fd unless it is to be our result.
634 */
635 int
636 to_upper_fd(int fd)
637 {
638 int i;
639
640 VTRACE(DBG_REDIR|DBG_OUTPUT, ("to_upper_fd(%d)", fd));
641 if (big_sh_fd < 10 || big_sh_fd >= user_fd_limit)
642 find_big_fd();
643 do {
644 i = fcntl(fd, F_DUPFD_CLOEXEC, big_sh_fd);
645 if (i >= 0) {
646 if (fd != i)
647 close(fd);
648 VTRACE(DBG_REDIR|DBG_OUTPUT, ("-> %d\n", i));
649 return i;
650 }
651 if (errno != EMFILE && errno != EINVAL)
652 break;
653 find_big_fd();
654 } while (big_sh_fd > 10);
655
656 /*
657 * If we wanted to move this fd to some random high number
658 * we certainly do not intend to pass it through exec, even
659 * if the reassignment failed.
660 */
661 (void)fcntl(fd, F_SETFD, FD_CLOEXEC);
662 VTRACE(DBG_REDIR|DBG_OUTPUT, (" fails ->%d\n", fd));
663 return fd;
664 }
665
666 void
667 register_sh_fd(int fd, void (*cb)(int, int))
668 {
669 struct shell_fds *fp;
670
671 fp = ckmalloc(sizeof (struct shell_fds));
672 if (fp != NULL) {
673 fp->nxt = sh_fd_list;
674 sh_fd_list = fp;
675
676 fp->fd = fd;
677 fp->cb = cb;
678 }
679 }
680
681 void
682 sh_close(int fd)
683 {
684 struct shell_fds **fpp, *fp;
685
686 fpp = &sh_fd_list;
687 while ((fp = *fpp) != NULL) {
688 if (fp->fd == fd) {
689 *fpp = fp->nxt;
690 ckfree(fp);
691 break;
692 }
693 fpp = &fp->nxt;
694 }
695 (void)close(fd);
696 }
697
698 STATIC struct shell_fds *
699 sh_fd(int fd)
700 {
701 struct shell_fds *fp;
702
703 for (fp = sh_fd_list; fp != NULL; fp = fp->nxt)
704 if (fp->fd == fd)
705 return fp;
706 return NULL;
707 }
708
709 STATIC int
710 pick_new_fd(int fd)
711 {
712 int to;
713
714 to = fcntl(fd, F_DUPFD_CLOEXEC, big_sh_fd);
715 if (to == -1 && big_sh_fd >= 22)
716 to = fcntl(fd, F_DUPFD_CLOEXEC, big_sh_fd/2);
717 if (to == -1)
718 to = fcntl(fd, F_DUPFD_CLOEXEC, fd + 1);
719 if (to == -1)
720 to = fcntl(fd, F_DUPFD_CLOEXEC, 10);
721 if (to == -1)
722 to = fcntl(fd, F_DUPFD_CLOEXEC, 3);
723 if (to == -1)
724 error("insufficient file descriptors available");
725 CLOEXEC(to);
726 return to;
727 }
728
729 STATIC void
730 renumber_sh_fd(struct shell_fds *fp)
731 {
732 int to;
733
734 if (fp == NULL)
735 return;
736
737 /*
738 * if we have had a collision, and the sh fd was a "big" one
739 * try moving the sh fd base to a higher number (if possible)
740 * so future sh fds are less likely to be in the user's sights
741 * (incl this one when moved)
742 */
743 if (fp->fd >= big_sh_fd)
744 find_big_fd();
745
746 to = pick_new_fd(fp->fd);
747
748 if (fp->fd == to) /* impossible? */
749 return;
750
751 VTRACE(DBG_REDIR, ("renumber_sh_fd: moved shell fd %d to %d\n",
752 fp->fd, to));
753
754 (*fp->cb)(fp->fd, to);
755 (void)close(fp->fd);
756 fp->fd = to;
757 }
758
759 static const struct flgnames {
760 const char *name;
761 uint16_t minch;
762 uint32_t value;
763 } nv[] = {
764 #ifdef O_APPEND
765 { "append", 2, O_APPEND },
766 #else
767 # define O_APPEND 0
768 #endif
769 #ifdef O_ASYNC
770 { "async", 2, O_ASYNC },
771 #else
772 # define O_ASYNC 0
773 #endif
774 #ifdef O_SYNC
775 { "sync", 2, O_SYNC },
776 #else
777 # define O_SYNC 0
778 #endif
779 #ifdef O_NONBLOCK
780 { "nonblock", 3, O_NONBLOCK },
781 #else
782 # define O_NONBLOCK 0
783 #endif
784 #ifdef O_FSYNC
785 { "fsync", 2, O_FSYNC },
786 #else
787 # define O_FSYNC 0
788 #endif
789 #ifdef O_DSYNC
790 { "dsync", 2, O_DSYNC },
791 #else
792 # define O_DSYNC 0
793 #endif
794 #ifdef O_RSYNC
795 { "rsync", 2, O_RSYNC },
796 #else
797 # define O_RSYNC 0
798 #endif
799 #ifdef O_ALT_IO
800 { "altio", 2, O_ALT_IO },
801 #else
802 # define O_ALT_IO 0
803 #endif
804 #ifdef O_DIRECT
805 { "direct", 2, O_DIRECT },
806 #else
807 # define O_DIRECT 0
808 #endif
809 #ifdef O_NOSIGPIPE
810 { "nosigpipe", 3, O_NOSIGPIPE },
811 #else
812 # define O_NOSIGPIPE 0
813 #endif
814
815 #define ALLFLAGS (O_APPEND|O_ASYNC|O_SYNC|O_NONBLOCK|O_DSYNC|O_RSYNC|\
816 O_ALT_IO|O_DIRECT|O_NOSIGPIPE)
817
818 #ifndef O_CLOEXEC
819 # define O_CLOEXEC ((~ALLFLAGS) ^ ((~ALLFLAGS) & ((~ALLFLAGS) - 1)))
820 #endif
821
822 /* for any system we support, close on exec is always defined */
823 { "cloexec", 2, O_CLOEXEC },
824 { 0, 0, 0 }
825 };
826
827 #ifndef O_ACCMODE
828 # define O_ACCMODE 0
829 #endif
830 #ifndef O_RDONLY
831 # define O_RDONLY 0
832 #endif
833 #ifndef O_WRONLY
834 # define O_WRONLY 0
835 #endif
836 #ifndef O_RWDR
837 # define O_RWDR 0
838 #endif
839 #ifndef O_SHLOCK
840 # define O_SHLOCK 0
841 #endif
842 #ifndef O_EXLOCK
843 # define O_EXLOCK 0
844 #endif
845 #ifndef O_NOFOLLOW
846 # define O_NOFOLLOW 0
847 #endif
848 #ifndef O_CREAT
849 # define O_CREAT 0
850 #endif
851 #ifndef O_TRUNC
852 # define O_TRUNC 0
853 #endif
854 #ifndef O_EXCL
855 # define O_EXCL 0
856 #endif
857 #ifndef O_NOCTTY
858 # define O_NOCTTY 0
859 #endif
860 #ifndef O_DIRECTORY
861 # define O_DIRECTORY 0
862 #endif
863 #ifndef O_REGULAR
864 # define O_REGULAR 0
865 #endif
866 /*
867 * flags that F_GETFL might return that we want to ignore
868 *
869 * F_GETFL should not actually return these, they're all just open()
870 * modifiers, rather than state, but just in case...
871 */
872 #define IGNFLAGS (O_ACCMODE|O_RDONLY|O_WRONLY|O_RDWR|O_SHLOCK|O_EXLOCK| \
873 O_NOFOLLOW|O_CREAT|O_TRUNC|O_EXCL|O_NOCTTY|O_DIRECTORY|O_REGULAR)
874
875 static int
876 getflags(int fd, int p)
877 {
878 int c, f;
879
880 if (sh_fd(fd) != NULL || saved_redirected_fd(fd) != NULL) {
881 if (!p)
882 return -1;
883 error("Can't get status for fd=%d (%s)", fd, strerror(EBADF));
884 }
885
886 if ((c = fcntl(fd, F_GETFD)) == -1) {
887 if (!p)
888 return -1;
889 error("Can't get status for fd=%d (%s)", fd, strerror(errno));
890 }
891 if ((f = fcntl(fd, F_GETFL)) == -1) {
892 if (!p)
893 return -1;
894 error("Can't get flags for fd=%d (%s)", fd, strerror(errno));
895 }
896 f &= ~IGNFLAGS; /* clear anything we know about, but ignore */
897 if (c & FD_CLOEXEC)
898 f |= O_CLOEXEC;
899 return f;
900 }
901
902 static void
903 printone(int fd, int p, int verbose, int pfd)
904 {
905 int f = getflags(fd, p);
906 const struct flgnames *fn;
907
908 if (f == -1)
909 return;
910
911 if (pfd)
912 outfmt(out1, "%d: ", fd);
913 for (fn = nv; fn->name; fn++) {
914 if (f & fn->value) {
915 outfmt(out1, "%s%s", verbose ? "+" : "", fn->name);
916 f &= ~fn->value;
917 } else if (verbose)
918 outfmt(out1, "-%s", fn->name);
919 else
920 continue;
921 if (f || (verbose && fn[1].name))
922 outfmt(out1, ",");
923 }
924 if (verbose && f) /* f should be normally be 0 */
925 outfmt(out1, " +%#x", f);
926 outfmt(out1, "\n");
927 }
928
929 static void
930 parseflags(char *s, int *p, int *n)
931 {
932 int *v, *w;
933 const struct flgnames *fn;
934 size_t len;
935
936 *p = 0;
937 *n = 0;
938 for (s = strtok(s, ","); s; s = strtok(NULL, ",")) {
939 switch (*s++) {
940 case '+':
941 v = p;
942 w = n;
943 break;
944 case '-':
945 v = n;
946 w = p;
947 break;
948 default:
949 error("Missing +/- indicator before flag %s", s-1);
950 }
951
952 len = strlen(s);
953 for (fn = nv; fn->name; fn++)
954 if (len >= fn->minch && strncmp(s,fn->name,len) == 0) {
955 *v |= fn->value;
956 *w &=~ fn->value;
957 break;
958 }
959 if (fn->name == 0)
960 error("Bad flag `%s'", s);
961 }
962 }
963
964 static void
965 setone(int fd, int pos, int neg, int verbose)
966 {
967 int f = getflags(fd, 1);
968 int n, cloexec;
969
970 if (f == -1)
971 return;
972
973 cloexec = -1;
974 if ((pos & O_CLOEXEC) && !(f & O_CLOEXEC))
975 cloexec = FD_CLOEXEC;
976 if ((neg & O_CLOEXEC) && (f & O_CLOEXEC))
977 cloexec = 0;
978
979 if (cloexec != -1 && fcntl(fd, F_SETFD, cloexec) == -1)
980 error("Can't set status for fd=%d (%s)", fd, strerror(errno));
981
982 pos &= ~O_CLOEXEC;
983 neg &= ~O_CLOEXEC;
984 f &= ~O_CLOEXEC;
985 n = f;
986 n |= pos;
987 n &= ~neg;
988 if (n != f && fcntl(fd, F_SETFL, n) == -1)
989 error("Can't set flags for fd=%d (%s)", fd, strerror(errno));
990 if (verbose)
991 printone(fd, 1, verbose, 1);
992 }
993
994 int
995 fdflagscmd(int argc, char *argv[])
996 {
997 char *num;
998 int verbose = 0, ch, pos = 0, neg = 0;
999 char *setflags = NULL;
1000
1001 optreset = 1; optind = 1; /* initialize getopt */
1002 while ((ch = getopt(argc, argv, ":vs:")) != -1)
1003 switch ((char)ch) {
1004 case 'v':
1005 verbose = 1;
1006 break;
1007 case 's':
1008 if (setflags)
1009 goto msg;
1010 setflags = optarg;
1011 break;
1012 case '?':
1013 default:
1014 msg:
1015 error("Usage: fdflags [-v] [-s <flags> fd] [fd...]");
1016 /* NOTREACHED */
1017 }
1018
1019 argc -= optind, argv += optind;
1020
1021 if (setflags)
1022 parseflags(setflags, &pos, &neg);
1023
1024 if (argc == 0) {
1025 int i;
1026
1027 if (setflags)
1028 goto msg;
1029
1030 for (i = 0; i <= max_user_fd; i++)
1031 printone(i, 0, verbose, 1);
1032 return 0;
1033 }
1034
1035 while ((num = *argv++) != NULL) {
1036 int fd = number(num);
1037
1038 while (num[0] == '0' && num[1] != '\0') /* skip 0's */
1039 num++;
1040 if (strlen(num) > 5 ||
1041 (fd >= user_fd_limit && fd > max_user_fd))
1042 error("%s: too big to be a file descriptor", num);
1043
1044 if (setflags)
1045 setone(fd, pos, neg, verbose);
1046 else
1047 printone(fd, 1, verbose, argc > 1);
1048 }
1049 return 0;
1050 }
1051
1052 #undef MAX /* in case we inherited them from somewhere */
1053 #undef MIN
1054
1055 #define MIN(a,b) (/*CONSTCOND*/((a)<=(b)) ? (a) : (b))
1056 #define MAX(a,b) (/*CONSTCOND*/((a)>=(b)) ? (a) : (b))
1057
1058 /* now make the compiler work for us... */
1059 #define MIN_REDIR MIN(MIN(MIN(MIN(NTO,NFROM), MIN(NTOFD,NFROMFD)), \
1060 MIN(MIN(NCLOBBER,NAPPEND), MIN(NHERE,NXHERE))), NFROMTO)
1061 #define MAX_REDIR MAX(MAX(MAX(MAX(NTO,NFROM), MAX(NTOFD,NFROMFD)), \
1062 MAX(MAX(NCLOBBER,NAPPEND), MAX(NHERE,NXHERE))), NFROMTO)
1063
1064 static const char *redir_sym[MAX_REDIR - MIN_REDIR + 1] = {
1065 [NTO - MIN_REDIR]= ">",
1066 [NFROM - MIN_REDIR]= "<",
1067 [NTOFD - MIN_REDIR]= ">&",
1068 [NFROMFD - MIN_REDIR]= "<&",
1069 [NCLOBBER - MIN_REDIR]= ">|",
1070 [NAPPEND - MIN_REDIR]= ">>",
1071 [NHERE - MIN_REDIR]= "<<",
1072 [NXHERE - MIN_REDIR]= "<<",
1073 [NFROMTO - MIN_REDIR]= "<>",
1074 };
1075
1076 int
1077 outredir(struct output *out, union node *n, int sep)
1078 {
1079 if (n == NULL)
1080 return 0;
1081 if (n->type < MIN_REDIR || n->type > MAX_REDIR ||
1082 redir_sym[n->type - MIN_REDIR] == NULL)
1083 return 0;
1084
1085 if (sep)
1086 outc(sep, out);
1087
1088 /*
1089 * ugly, but all redir node types have "fd" in same slot...
1090 * (and code other places assumes it as well)
1091 */
1092 if ((redir_sym[n->type - MIN_REDIR][0] == '<' && n->nfile.fd != 0) ||
1093 (redir_sym[n->type - MIN_REDIR][0] == '>' && n->nfile.fd != 1))
1094 outfmt(out, "%d", n->nfile.fd);
1095
1096 outstr(redir_sym[n->type - MIN_REDIR], out);
1097
1098 switch (n->type) {
1099 case NHERE:
1100 outstr("'...'", out);
1101 break;
1102 case NXHERE:
1103 outstr("...", out);
1104 break;
1105 case NTOFD:
1106 case NFROMFD:
1107 if (n->ndup.dupfd < 0)
1108 outc('-', out);
1109 else
1110 outfmt(out, "%d", n->ndup.dupfd);
1111 break;
1112 default:
1113 outstr(n->nfile.expfname, out);
1114 break;
1115 }
1116 return 1;
1117 }
1118