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