1 /* redir.c -- Functions to perform input and output redirection. */
3 /* Copyright (C) 1997 Free Software Foundation, Inc.
5 This file is part of GNU Bash, the Bourne Again SHell.
7 Bash is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 Bash is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
15 License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Bash; see the file COPYING. If not, write to the Free
19 Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */
22 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
24 #endif /* _AIX && RISC6000 && !__GNUC__ */
27 #include "bashtypes.h"
29 # include <sys/file.h>
32 #include "posixstat.h"
34 #if defined (HAVE_UNISTD_H)
49 #include "execute_cmd.h"
52 #if defined (BUFFERED_INPUT)
56 extern int posixly_correct;
57 extern int interactive, interactive_shell;
58 extern REDIRECT *redirection_undo_list;
59 extern REDIRECT *exec_redirection_undo_list;
61 /* Static functions defined and used in this file. */
62 static void add_undo_close_redirect ();
63 static void add_exec_redirect ();
64 static int add_undo_redirect ();
65 static int do_redirection_internal ();
66 static int expandable_redirection_filename ();
67 static int stdin_redirection ();
69 /* Spare redirector used when translating [N]>&WORD or [N]<&WORD to a new
70 redirection and when creating the redirection undo list. */
73 /* Set to errno when a here document cannot be created for some reason.
74 Used to print a reasonable error message. */
75 static int heredoc_errno;
78 redirection_error (temp, error)
85 if (expandable_redirection_filename (temp))
87 if (posixly_correct && interactive_shell == 0)
89 oflags = temp->redirectee.filename->flags;
90 temp->redirectee.filename->flags |= W_NOGLOB;
92 filename = redirection_expand (temp->redirectee.filename);
93 if (posixly_correct && interactive_shell == 0)
94 temp->redirectee.filename->flags = oflags;
96 filename = savestring (temp->redirectee.filename->word);
99 filename = xmalloc (1);
104 filename = itos (temp->redirectee.dest);
108 case AMBIGUOUS_REDIRECT:
109 internal_error ("%s: ambiguous redirect", filename);
112 case NOCLOBBER_REDIRECT:
113 internal_error ("%s: cannot overwrite existing file", filename);
116 #if defined (RESTRICTED_SHELL)
117 case RESTRICTED_REDIRECT:
118 internal_error ("%s: restricted: cannot redirect output", filename);
120 #endif /* RESTRICTED_SHELL */
122 case HEREDOC_REDIRECT:
123 internal_error ("cannot create temp file for here document: %s", strerror (heredoc_errno));
127 internal_error ("%s: %s", filename, strerror (error));
134 /* Perform the redirections on LIST. If FOR_REAL, then actually make
135 input and output file descriptors, otherwise just do whatever is
136 neccessary for side effecting. INTERNAL says to remember how to
137 undo the redirections later, if non-zero. If SET_CLEXEC is non-zero,
138 file descriptors opened in do_redirection () have their close-on-exec
141 do_redirections (list, for_real, internal, set_clexec)
143 int for_real, internal, set_clexec;
150 if (redirection_undo_list)
152 dispose_redirects (redirection_undo_list);
153 redirection_undo_list = (REDIRECT *)NULL;
155 if (exec_redirection_undo_list)
156 dispose_exec_redirects ();
159 for (temp = list; temp; temp = temp->next)
161 error = do_redirection_internal (temp, for_real, internal, set_clexec);
164 redirection_error (temp, error);
171 /* Return non-zero if the redirection pointed to by REDIRECT has a
172 redirectee.filename that can be expanded. */
174 expandable_redirection_filename (redirect)
177 switch (redirect->instruction)
179 case r_output_direction:
181 case r_input_direction:
182 case r_inputa_direction:
186 case r_duplicating_input_word:
187 case r_duplicating_output_word:
195 /* Expand the word in WORD returning a string. If WORD expands to
196 multiple words (or no words), then return NULL. */
198 redirection_expand (word)
202 WORD_LIST *tlist1, *tlist2;
205 w = copy_word (word);
207 w->flags |= W_NOSPLIT;
209 tlist1 = make_word_list (w, (WORD_LIST *)NULL);
210 tlist2 = expand_words_no_vars (tlist1);
211 dispose_words (tlist1);
213 if (!tlist2 || tlist2->next)
215 /* We expanded to no words, or to more than a single word.
216 Dispose of the word list and return NULL. */
218 dispose_words (tlist2);
219 return ((char *)NULL);
221 result = string_list (tlist2); /* XXX savestring (tlist2->word->word)? */
222 dispose_words (tlist2);
226 /* Write the text of the here document pointed to by REDIRECTEE to the file
227 descriptor FD, which is already open to a temp file. Return 0 if the
228 write is successful, otherwise return errno. */
230 write_here_document (fd, redirectee)
232 WORD_DESC *redirectee;
235 int document_len, fd2;
237 register WORD_LIST *t, *tlist;
239 /* Expand the text if the word that was specified had
240 no quoting. The text that we expand is treated
241 exactly as if it were surrounded by double quotes. */
243 if (redirectee->flags & W_QUOTED)
245 document = redirectee->word;
246 document_len = strlen (document);
247 /* Set errno to something reasonable if the write fails. */
248 if (write (fd, document, document_len) < document_len)
258 tlist = expand_string (redirectee->word, Q_HERE_DOCUMENT);
261 /* Try using buffered I/O (stdio) and writing a word
262 at a time, letting stdio do the work of buffering
263 for us rather than managing our own strings. Most
264 stdios are not particularly fast, however -- this
265 may need to be reconsidered later. */
266 if ((fd2 = dup (fd)) < 0 || (fp = fdopen (fd2, "w")) == NULL)
273 for (t = tlist; t; t = t->next)
275 /* This is essentially the body of
276 string_list_internal expanded inline. */
277 document = t->word->word;
278 document_len = strlen (document);
280 putc (' ', fp); /* separator */
281 fwrite (document, document_len, 1, fp);
288 dispose_words (tlist);
293 dispose_words (tlist);
298 /* Create a temporary file holding the text of the here document pointed to
299 by REDIRECTEE, and return a file descriptor open for reading to the temp
300 file. Return -1 on any error, and make sure errno is set appropriately. */
302 here_document_to_fd (redirectee)
303 WORD_DESC *redirectee;
311 /* Make the filename for the temp file. */
312 sprintf (filename, "/tmp/t%d-%d-sh", (int)getpid (), fnum++);
314 /* Make sure we open it exclusively. */
315 fd = open (filename, O_TRUNC | O_WRONLY | O_CREAT | O_EXCL, 0600);
317 while (fd < 0 && errno == EEXIST);
319 /* If we failed for some reason other than the file existing, abort */
323 errno = r = 0; /* XXX */
324 /* write_here_document returns 0 on success, errno on failure. */
325 if (redirectee->word)
326 r = write_here_document (fd, redirectee);
336 /* In an attempt to avoid races, we close the first fd only after opening
338 /* Make the document really temporary. Also make it the input. */
339 fd2 = open (filename, O_RDONLY, 0600);
351 if (unlink (filename) < 0)
363 #define RF_DEVSTDERR 2
364 #define RF_DEVSTDIN 3
365 #define RF_DEVSTDOUT 4
369 /* A list of pattern/value pairs for filenames that the redirection
370 code handles specially. */
371 static STRING_INT_ALIST _redir_special_filenames[] = {
372 #if !defined (HAVE_DEV_FD)
373 { "/dev/fd/[0-9]*", RF_DEVFD },
375 #if !defined (HAVE_DEV_STDIN)
376 { "/dev/stderr", RF_DEVSTDERR },
377 { "/dev/stdin", RF_DEVSTDIN },
378 { "/dev/stdout", RF_DEVSTDOUT },
380 #if defined (NETWORK_REDIRECTIONS)
381 { "/dev/tcp/*/*", RF_DEVTCP },
382 { "/dev/udp/*/*", RF_DEVUDP },
388 redir_special_open (spec, filename, flags, mode, ri)
392 enum r_instruction ri;
400 #if !defined (HAVE_DEV_FD)
402 if (legal_number, filename+8, &lfd)
403 fd = fcntl ((int)lfd, F_DUPFD, 10);
405 fd = AMBIGUOUS_REDIRECT;
409 #if !defined (HAVE_DEV_STDIN)
411 fd = fcntl (0, F_DUPFD, 10);
414 fd = fcntl (1, F_DUPFD, 10);
417 fd = fcntl (2, F_DUPFD, 10);
421 #if defined (NETWORK_REDIRECTIONS)
424 #if defined (HAVE_NETWORK)
425 fd = netopen (filename);
427 internal_warning ("/dev/(tcp|udp)/host/port not supported without networking");
428 fd = open (filename, flags, mode);
431 #endif /* NETWORK_REDIRECTIONS */
437 /* Open FILENAME with FLAGS in noclobber mode, hopefully avoiding most
438 race conditions and avoiding the problem where the file is replaced
439 between the stat(2) and open(2). */
441 noclobber_open (filename, flags, mode, ri)
444 enum r_instruction ri;
447 struct stat finfo, finfo2;
449 /* If the file exists and is a regular file, return an error
451 r = stat (filename, &finfo);
452 if (r == 0 && (S_ISREG (finfo.st_mode)))
453 return (NOCLOBBER_REDIRECT);
455 /* If the file was not present (r != 0), make sure we open it
456 exclusively so that if it is created before we open it, our open
457 will fail. Make sure that we do not truncate an existing file.
458 Note that we don't turn on O_EXCL unless the stat failed -- if
459 the file was not a regular file, we leave O_EXCL off. */
463 fd = open (filename, flags|O_EXCL, mode);
464 return ((fd < 0 && errno == EEXIST) ? NOCLOBBER_REDIRECT : fd);
466 fd = open (filename, flags, mode);
468 /* If the open failed, return the file descriptor right away. */
470 return (errno == EEXIST ? NOCLOBBER_REDIRECT : fd);
472 /* OK, the open succeeded, but the file may have been changed from a
473 non-regular file to a regular file between the stat and the open.
474 We are assuming that the O_EXCL open handles the case where FILENAME
475 did not exist and is symlinked to an existing file between the stat
478 /* If we can open it and fstat the file descriptor, and neither check
479 revealed that it was a regular file, and the file has not been replaced,
480 return the file descriptor. */
481 if ((fstat (fd, &finfo2) == 0) && (S_ISREG (finfo2.st_mode) == 0) &&
482 r == 0 && (S_ISREG (finfo.st_mode) == 0) &&
483 same_file (filename, filename, &finfo, &finfo2))
486 /* The file has been replaced. badness. */
489 return (NOCLOBBER_REDIRECT);
493 redir_open (filename, flags, mode, ri)
496 enum r_instruction ri;
500 r = find_string_in_alist (filename, _redir_special_filenames, 1);
502 return (redir_special_open (r, filename, flags, mode, ri));
504 /* If we are in noclobber mode, you are not allowed to overwrite
505 existing files. Check before opening. */
506 if (noclobber && OUTPUT_REDIRECT (ri))
508 fd = noclobber_open (filename, flags, mode, ri);
509 if (fd == NOCLOBBER_REDIRECT)
510 return (NOCLOBBER_REDIRECT);
514 fd = open (filename, flags, mode);
516 if ((fd < 0) && (errno == EACCES))
517 fd = open (filename, flags & ~O_CREAT, mode);
524 /* Do the specific redirection requested. Returns errno or one of the
525 special redirection errors (*_REDIRECT) in case of error, 0 on success.
526 If FOR_REAL is zero, then just do whatever is neccessary to produce the
527 appropriate side effects. REMEMBERING, if non-zero, says to remember
528 how to undo each redirection. If SET_CLEXEC is non-zero, then
529 we set all file descriptors > 2 that we open to be close-on-exec. */
531 do_redirection_internal (redirect, for_real, remembering, set_clexec)
533 int for_real, remembering, set_clexec;
535 WORD_DESC *redirectee;
536 int redir_fd, fd, redirector, r, oflags;
537 char *redirectee_word;
538 enum r_instruction ri;
539 REDIRECT *new_redirect;
541 redirectee = redirect->redirectee.filename;
542 redir_fd = redirect->redirectee.dest;
543 redirector = redirect->redirector;
544 ri = redirect->instruction;
546 if (ri == r_duplicating_input_word || ri == r_duplicating_output_word)
548 /* We have [N]>&WORD or [N]<&WORD. Expand WORD, then translate
549 the redirection into a new one and continue. */
550 redirectee_word = redirection_expand (redirectee);
552 if (redirectee_word == 0)
553 return (AMBIGUOUS_REDIRECT);
554 else if (redirectee_word[0] == '-' && redirectee_word[1] == '\0')
557 new_redirect = make_redirection (redirector, r_close_this, rd);
559 else if (all_digits (redirectee_word))
561 if (ri == r_duplicating_input_word)
563 rd.dest = atol (redirectee_word);
564 new_redirect = make_redirection (redirector, r_duplicating_input, rd);
568 rd.dest = atol (redirectee_word);
569 new_redirect = make_redirection (redirector, r_duplicating_output, rd);
572 else if (ri == r_duplicating_output_word && redirector == 1)
574 if (posixly_correct == 0)
576 rd.filename = make_bare_word (redirectee_word);
577 new_redirect = make_redirection (1, r_err_and_out, rd);
580 new_redirect = copy_redirect (redirect);
584 free (redirectee_word);
585 return (AMBIGUOUS_REDIRECT);
588 free (redirectee_word);
590 /* Set up the variables needed by the rest of the function from the
592 if (new_redirect->instruction == r_err_and_out)
596 /* Copy the word without allocating any memory that must be
598 redirectee = (WORD_DESC *)alloca (sizeof (WORD_DESC));
599 xbcopy ((char *)new_redirect->redirectee.filename,
600 (char *)redirectee, sizeof (WORD_DESC));
602 alloca_hack = (char *)
603 alloca (1 + strlen (new_redirect->redirectee.filename->word));
604 redirectee->word = alloca_hack;
605 strcpy (redirectee->word, new_redirect->redirectee.filename->word);
608 /* It's guaranteed to be an integer, and shouldn't be freed. */
609 redirectee = new_redirect->redirectee.filename;
611 redir_fd = new_redirect->redirectee.dest;
612 redirector = new_redirect->redirector;
613 ri = new_redirect->instruction;
615 /* Overwrite the flags element of the old redirect with the new value. */
616 redirect->flags = new_redirect->flags;
617 dispose_redirects (new_redirect);
622 case r_output_direction:
624 case r_input_direction:
625 case r_inputa_direction:
626 case r_err_and_out: /* command &>filename */
629 if (posixly_correct && interactive_shell == 0)
631 oflags = redirectee->flags;
632 redirectee->flags |= W_NOGLOB;
634 redirectee_word = redirection_expand (redirectee);
635 if (posixly_correct && interactive_shell == 0)
636 redirectee->flags = oflags;
638 if (redirectee_word == 0)
639 return (AMBIGUOUS_REDIRECT);
641 #if defined (RESTRICTED_SHELL)
642 if (restricted && (WRITE_REDIRECT (ri)))
644 free (redirectee_word);
645 return (RESTRICTED_REDIRECT);
647 #endif /* RESTRICTED_SHELL */
649 fd = redir_open (redirectee_word, redirect->flags, 0666, ri);
650 free (redirectee_word);
652 if (fd == NOCLOBBER_REDIRECT)
661 /* Only setup to undo it if the thing to undo is active. */
662 if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
663 add_undo_redirect (redirector);
665 add_undo_close_redirect (redirector);
667 #if defined (BUFFERED_INPUT)
668 check_bash_input (redirector);
671 if ((fd != redirector) && (dup2 (fd, redirector) < 0))
674 #if defined (BUFFERED_INPUT)
675 /* Do not change the buffered stream for an implicit redirection
676 of /dev/null to fd 0 for asynchronous commands without job
677 control (r_inputa_direction). */
678 if (ri == r_input_direction || ri == r_input_output)
679 duplicate_buffered_stream (fd, redirector);
680 #endif /* BUFFERED_INPUT */
683 * If we're remembering, then this is the result of a while, for
684 * or until loop with a loop redirection, or a function/builtin
685 * executing in the parent shell with a redirection. In the
686 * function/builtin case, we want to set all file descriptors > 2
687 * to be close-on-exec to duplicate the effect of the old
688 * for i = 3 to NOFILE close(i) loop. In the case of the loops,
689 * both sh and ksh leave the file descriptors open across execs.
690 * The Posix standard mentions only the exec builtin.
692 if (set_clexec && (redirector > 2))
693 SET_CLOSE_ON_EXEC (redirector);
696 if (fd != redirector)
698 #if defined (BUFFERED_INPUT)
699 if (INPUT_REDIRECT (ri))
700 close_buffered_fd (fd);
702 #endif /* !BUFFERED_INPUT */
703 close (fd); /* Don't close what we just opened! */
706 /* If we are hacking both stdout and stderr, do the stderr
708 if (ri == r_err_and_out)
713 add_undo_redirect (2);
720 case r_reading_until:
721 case r_deblank_reading_until:
722 /* REDIRECTEE is a pointer to a WORD_DESC containing the text of
723 the new input. Place it in a temporary file. */
726 fd = here_document_to_fd (redirectee);
730 heredoc_errno = errno;
731 return (HEREDOC_REDIRECT);
737 /* Only setup to undo it if the thing to undo is active. */
738 if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
739 add_undo_redirect (redirector);
741 add_undo_close_redirect (redirector);
743 #if defined (BUFFERED_INPUT)
744 check_bash_input (redirector);
746 if (fd != redirector && dup2 (fd, redirector) < 0)
753 #if defined (BUFFERED_INPUT)
754 duplicate_buffered_stream (fd, redirector);
757 if (set_clexec && (redirector > 2))
758 SET_CLOSE_ON_EXEC (redirector);
761 if (fd != redirector)
762 #if defined (BUFFERED_INPUT)
763 close_buffered_fd (fd);
770 case r_duplicating_input:
771 case r_duplicating_output:
772 if (for_real && (redir_fd != redirector))
775 /* Only setup to undo it if the thing to undo is active. */
776 if (fcntl (redirector, F_GETFD, 0) != -1)
777 add_undo_redirect (redirector);
779 add_undo_close_redirect (redirector);
781 #if defined (BUFFERED_INPUT)
782 check_bash_input (redirector);
785 /* This is correct. 2>&1 means dup2 (1, 2); */
786 if (dup2 (redir_fd, redirector) < 0)
789 #if defined (BUFFERED_INPUT)
790 if (ri == r_duplicating_input)
791 duplicate_buffered_stream (redir_fd, redirector);
792 #endif /* BUFFERED_INPUT */
794 /* First duplicate the close-on-exec state of redirectee. dup2
795 leaves the flag unset on the new descriptor, which means it
796 stays open. Only set the close-on-exec bit for file descriptors
797 greater than 2 in any case, since 0-2 should always be open
798 unless closed by something like `exec 2<&-'. */
799 /* if ((already_set || set_unconditionally) && (ok_to_set))
801 if (((fcntl (redir_fd, F_GETFD, 0) == 1) || set_clexec) &&
803 SET_CLOSE_ON_EXEC (redirector);
810 if (remembering && (fcntl (redirector, F_GETFD, 0) != -1))
811 add_undo_redirect (redirector);
813 #if defined (BUFFERED_INPUT)
814 check_bash_input (redirector);
815 close_buffered_fd (redirector);
816 #else /* !BUFFERED_INPUT */
818 #endif /* !BUFFERED_INPUT */
822 case r_duplicating_input_word:
823 case r_duplicating_output_word:
829 #define SHELL_FD_BASE 10
831 /* Remember the file descriptor associated with the slot FD,
832 on REDIRECTION_UNDO_LIST. Note that the list will be reversed
833 before it is executed. Any redirections that need to be undone
834 even if REDIRECTION_UNDO_LIST is discarded by the exec builtin
835 are also saved on EXEC_REDIRECTION_UNDO_LIST. */
837 add_undo_redirect (fd)
840 int new_fd, clexec_flag;
841 REDIRECT *new_redirect, *closer, *dummy_redirect;
843 new_fd = fcntl (fd, F_DUPFD, SHELL_FD_BASE);
847 sys_error ("redirection error");
851 clexec_flag = fcntl (fd, F_GETFD, 0);
854 closer = make_redirection (new_fd, r_close_this, rd);
855 dummy_redirect = copy_redirects (closer);
857 rd.dest = (long)new_fd;
858 new_redirect = make_redirection (fd, r_duplicating_output, rd);
859 new_redirect->next = closer;
861 closer->next = redirection_undo_list;
862 redirection_undo_list = new_redirect;
864 /* Save redirections that need to be undone even if the undo list
865 is thrown away by the `exec' builtin. */
866 add_exec_redirect (dummy_redirect);
868 /* File descriptors used only for saving others should always be
869 marked close-on-exec. Unfortunately, we have to preserve the
870 close-on-exec state of the file descriptor we are saving, since
871 fcntl (F_DUPFD) sets the new file descriptor to remain open
872 across execs. If, however, the file descriptor whose state we
873 are saving is <= 2, we can just set the close-on-exec flag,
874 because file descriptors 0-2 should always be open-on-exec,
875 and the restore above in do_redirection() will take care of it. */
876 if (clexec_flag || fd < 3)
877 SET_CLOSE_ON_EXEC (new_fd);
882 /* Set up to close FD when we are finished with the current command
883 and its redirections. */
885 add_undo_close_redirect (fd)
891 closer = make_redirection (fd, r_close_this, rd);
892 closer->next = redirection_undo_list;
893 redirection_undo_list = closer;
897 add_exec_redirect (dummy_redirect)
898 REDIRECT *dummy_redirect;
900 dummy_redirect->next = exec_redirection_undo_list;
901 exec_redirection_undo_list = dummy_redirect;
904 /* Return 1 if the redirection specified by RI and REDIRECTOR alters the
907 stdin_redirection (ri, redirector)
908 enum r_instruction ri;
913 case r_input_direction:
914 case r_inputa_direction:
916 case r_reading_until:
917 case r_deblank_reading_until:
919 case r_duplicating_input:
920 case r_duplicating_input_word:
922 return (redirector == 0);
923 case r_output_direction:
925 case r_duplicating_output:
928 case r_duplicating_output_word:
934 /* Return non-zero if any of the redirections in REDIRS alter the standard
937 stdin_redirects (redirs)
943 for (n = 0, rp = redirs; rp; rp = rp->next)
944 n += stdin_redirection (rp->instruction, rp->redirector);