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