]> git.ipfire.org Git - thirdparty/bash.git/blob - redir.c
commit bash-20090806 snapshot
[thirdparty/bash.git] / redir.c
1 /* redir.c -- Functions to perform input and output redirection. */
2
3 /* Copyright (C) 1997-2009 Free Software Foundation, Inc.
4
5 This file is part of GNU Bash, the Bourne Again SHell.
6
7 Bash is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 Bash is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Bash. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "config.h"
22
23 #if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
24 #pragma alloca
25 #endif /* _AIX && RISC6000 && !__GNUC__ */
26
27 #include <stdio.h>
28 #include "bashtypes.h"
29 #if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
30 # include <sys/file.h>
31 #endif
32 #include "filecntl.h"
33 #include "posixstat.h"
34
35 #if defined (HAVE_UNISTD_H)
36 # include <unistd.h>
37 #endif
38
39 #include <errno.h>
40
41 #if !defined (errno)
42 extern int errno;
43 #endif
44
45 #include "bashansi.h"
46 #include "bashintl.h"
47 #include "memalloc.h"
48
49 #define NEED_FPURGE_DECL
50
51 #include "shell.h"
52 #include "flags.h"
53 #include "execute_cmd.h"
54 #include "redir.h"
55
56 #if defined (BUFFERED_INPUT)
57 # include "input.h"
58 #endif
59
60 #define SHELL_FD_BASE 10
61
62 int expanding_redir;
63
64 extern int posixly_correct;
65 extern REDIRECT *redirection_undo_list;
66 extern REDIRECT *exec_redirection_undo_list;
67
68 /* Static functions defined and used in this file. */
69 static void add_undo_close_redirect __P((int));
70 static void add_exec_redirect __P((REDIRECT *));
71 static int add_undo_redirect __P((int, enum r_instruction, int));
72 static int expandable_redirection_filename __P((REDIRECT *));
73 static int stdin_redirection __P((enum r_instruction, int));
74 static int undoablefd __P((int));
75 static int do_redirection_internal __P((REDIRECT *, int));
76
77 static int write_here_document __P((int, WORD_DESC *));
78 static int write_here_string __P((int, WORD_DESC *));
79 static int here_document_to_fd __P((WORD_DESC *, enum r_instruction));
80
81 static int redir_special_open __P((int, char *, int, int, enum r_instruction));
82 static int noclobber_open __P((char *, int, int, enum r_instruction));
83 static int redir_open __P((char *, int, int, enum r_instruction));
84
85 /* Spare redirector used when translating [N]>&WORD[-] or [N]<&WORD[-] to
86 a new redirection and when creating the redirection undo list. */
87 static REDIRECTEE rd;
88
89 /* Set to errno when a here document cannot be created for some reason.
90 Used to print a reasonable error message. */
91 static int heredoc_errno;
92
93 void
94 redirection_error (temp, error)
95 REDIRECT *temp;
96 int error;
97 {
98 char *filename, *allocname;
99 int oflags;
100
101 allocname = 0;
102 if (temp->redirector < 0)
103 /* This can happen when read_token_word encounters overflow, like in
104 exec 4294967297>x */
105 filename = _("file descriptor out of range");
106 #ifdef EBADF
107 /* This error can never involve NOCLOBBER */
108 else if (error != NOCLOBBER_REDIRECT && temp->redirector >= 0 && error == EBADF)
109 {
110 /* If we're dealing with two file descriptors, we have to guess about
111 which one is invalid; in the cases of r_{duplicating,move}_input and
112 r_{duplicating,move}_output we're here because dup2() failed. */
113 switch (temp->instruction)
114 {
115 case r_duplicating_input:
116 case r_duplicating_output:
117 case r_move_input:
118 case r_move_output:
119 filename = allocname = itos (temp->redirectee.dest);
120 break;
121 default:
122 filename = allocname = itos (temp->redirector);
123 break;
124 }
125 }
126 #endif
127 else if (expandable_redirection_filename (temp))
128 {
129 if (posixly_correct && interactive_shell == 0)
130 {
131 oflags = temp->redirectee.filename->flags;
132 temp->redirectee.filename->flags |= W_NOGLOB;
133 }
134 filename = allocname = redirection_expand (temp->redirectee.filename);
135 if (posixly_correct && interactive_shell == 0)
136 temp->redirectee.filename->flags = oflags;
137 if (filename == 0)
138 filename = temp->redirectee.filename->word;
139 }
140 else if (temp->redirectee.dest < 0)
141 filename = "file descriptor out of range";
142 else
143 filename = allocname = itos (temp->redirectee.dest);
144
145 switch (error)
146 {
147 case AMBIGUOUS_REDIRECT:
148 internal_error (_("%s: ambiguous redirect"), filename);
149 break;
150
151 case NOCLOBBER_REDIRECT:
152 internal_error (_("%s: cannot overwrite existing file"), filename);
153 break;
154
155 #if defined (RESTRICTED_SHELL)
156 case RESTRICTED_REDIRECT:
157 internal_error (_("%s: restricted: cannot redirect output"), filename);
158 break;
159 #endif /* RESTRICTED_SHELL */
160
161 case HEREDOC_REDIRECT:
162 internal_error (_("cannot create temp file for here-document: %s"), strerror (heredoc_errno));
163 break;
164
165 default:
166 internal_error ("%s: %s", filename, strerror (error));
167 break;
168 }
169
170 FREE (allocname);
171 }
172
173 /* Perform the redirections on LIST. If flags & RX_ACTIVE, then actually
174 make input and output file descriptors, otherwise just do whatever is
175 neccessary for side effecting. flags & RX_UNDOABLE says to remember
176 how to undo the redirections later, if non-zero. If flags & RX_CLEXEC
177 is non-zero, file descriptors opened in do_redirection () have their
178 close-on-exec flag set. */
179 int
180 do_redirections (list, flags)
181 REDIRECT *list;
182 int flags;
183 {
184 int error;
185 REDIRECT *temp;
186
187 if (flags & RX_UNDOABLE)
188 {
189 if (redirection_undo_list)
190 {
191 dispose_redirects (redirection_undo_list);
192 redirection_undo_list = (REDIRECT *)NULL;
193 }
194 if (exec_redirection_undo_list)
195 dispose_exec_redirects ();
196 }
197
198 for (temp = list; temp; temp = temp->next)
199 {
200 error = do_redirection_internal (temp, flags);
201 if (error)
202 {
203 redirection_error (temp, error);
204 return (error);
205 }
206 }
207 return (0);
208 }
209
210 /* Return non-zero if the redirection pointed to by REDIRECT has a
211 redirectee.filename that can be expanded. */
212 static int
213 expandable_redirection_filename (redirect)
214 REDIRECT *redirect;
215 {
216 switch (redirect->instruction)
217 {
218 case r_output_direction:
219 case r_appending_to:
220 case r_input_direction:
221 case r_inputa_direction:
222 case r_err_and_out:
223 case r_append_err_and_out:
224 case r_input_output:
225 case r_output_force:
226 case r_duplicating_input_word:
227 case r_duplicating_output_word:
228 case r_move_input_word:
229 case r_move_output_word:
230 return 1;
231
232 default:
233 return 0;
234 }
235 }
236
237 /* Expand the word in WORD returning a string. If WORD expands to
238 multiple words (or no words), then return NULL. */
239 char *
240 redirection_expand (word)
241 WORD_DESC *word;
242 {
243 char *result;
244 WORD_LIST *tlist1, *tlist2;
245 WORD_DESC *w;
246
247 w = copy_word (word);
248 if (posixly_correct)
249 w->flags |= W_NOSPLIT;
250
251 tlist1 = make_word_list (w, (WORD_LIST *)NULL);
252 expanding_redir = 1;
253 tlist2 = expand_words_no_vars (tlist1);
254 expanding_redir = 0;
255 dispose_words (tlist1);
256
257 if (!tlist2 || tlist2->next)
258 {
259 /* We expanded to no words, or to more than a single word.
260 Dispose of the word list and return NULL. */
261 if (tlist2)
262 dispose_words (tlist2);
263 return ((char *)NULL);
264 }
265 result = string_list (tlist2); /* XXX savestring (tlist2->word->word)? */
266 dispose_words (tlist2);
267 return (result);
268 }
269
270 static int
271 write_here_string (fd, redirectee)
272 int fd;
273 WORD_DESC *redirectee;
274 {
275 char *herestr;
276 int herelen, n, e;
277
278 expanding_redir = 1;
279 herestr = expand_string_to_string (redirectee->word, 0);
280 expanding_redir = 0;
281 herelen = STRLEN (herestr);
282
283 n = write (fd, herestr, herelen);
284 if (n == herelen)
285 {
286 n = write (fd, "\n", 1);
287 herelen = 1;
288 }
289 e = errno;
290 FREE (herestr);
291 if (n != herelen)
292 {
293 if (e == 0)
294 e = ENOSPC;
295 return e;
296 }
297 return 0;
298 }
299
300 /* Write the text of the here document pointed to by REDIRECTEE to the file
301 descriptor FD, which is already open to a temp file. Return 0 if the
302 write is successful, otherwise return errno. */
303 static int
304 write_here_document (fd, redirectee)
305 int fd;
306 WORD_DESC *redirectee;
307 {
308 char *document;
309 int document_len, fd2;
310 FILE *fp;
311 register WORD_LIST *t, *tlist;
312
313 /* Expand the text if the word that was specified had
314 no quoting. The text that we expand is treated
315 exactly as if it were surrounded by double quotes. */
316
317 if (redirectee->flags & W_QUOTED)
318 {
319 document = redirectee->word;
320 document_len = strlen (document);
321 /* Set errno to something reasonable if the write fails. */
322 if (write (fd, document, document_len) < document_len)
323 {
324 if (errno == 0)
325 errno = ENOSPC;
326 return (errno);
327 }
328 else
329 return 0;
330 }
331
332 expanding_redir = 1;
333 tlist = expand_string (redirectee->word, Q_HERE_DOCUMENT);
334 expanding_redir = 0;
335
336 if (tlist)
337 {
338 /* Try using buffered I/O (stdio) and writing a word
339 at a time, letting stdio do the work of buffering
340 for us rather than managing our own strings. Most
341 stdios are not particularly fast, however -- this
342 may need to be reconsidered later. */
343 if ((fd2 = dup (fd)) < 0 || (fp = fdopen (fd2, "w")) == NULL)
344 {
345 if (fd2 >= 0)
346 close (fd2);
347 return (errno);
348 }
349 errno = 0;
350 for (t = tlist; t; t = t->next)
351 {
352 /* This is essentially the body of
353 string_list_internal expanded inline. */
354 document = t->word->word;
355 document_len = strlen (document);
356 if (t != tlist)
357 putc (' ', fp); /* separator */
358 fwrite (document, document_len, 1, fp);
359 if (ferror (fp))
360 {
361 if (errno == 0)
362 errno = ENOSPC;
363 fd2 = errno;
364 fclose(fp);
365 dispose_words (tlist);
366 return (fd2);
367 }
368 }
369 dispose_words (tlist);
370 if (fclose (fp) != 0)
371 {
372 if (errno == 0)
373 errno = ENOSPC;
374 return (errno);
375 }
376 }
377 return 0;
378 }
379
380 /* Create a temporary file holding the text of the here document pointed to
381 by REDIRECTEE, and return a file descriptor open for reading to the temp
382 file. Return -1 on any error, and make sure errno is set appropriately. */
383 static int
384 here_document_to_fd (redirectee, ri)
385 WORD_DESC *redirectee;
386 enum r_instruction ri;
387 {
388 char *filename;
389 int r, fd, fd2;
390
391 fd = sh_mktmpfd ("sh-thd", MT_USERANDOM|MT_USETMPDIR, &filename);
392
393 /* If we failed for some reason other than the file existing, abort */
394 if (fd < 0)
395 {
396 FREE (filename);
397 return (fd);
398 }
399
400 errno = r = 0; /* XXX */
401 /* write_here_document returns 0 on success, errno on failure. */
402 if (redirectee->word)
403 r = (ri != r_reading_string) ? write_here_document (fd, redirectee)
404 : write_here_string (fd, redirectee);
405
406 if (r)
407 {
408 close (fd);
409 unlink (filename);
410 free (filename);
411 errno = r;
412 return (-1);
413 }
414
415 /* In an attempt to avoid races, we close the first fd only after opening
416 the second. */
417 /* Make the document really temporary. Also make it the input. */
418 fd2 = open (filename, O_RDONLY, 0600);
419
420 if (fd2 < 0)
421 {
422 r = errno;
423 unlink (filename);
424 free (filename);
425 close (fd);
426 errno = r;
427 return -1;
428 }
429
430 close (fd);
431 if (unlink (filename) < 0)
432 {
433 r = errno;
434 #if defined (__CYGWIN__)
435 /* Under CygWin 1.1.0, the unlink will fail if the file is
436 open. This hack will allow the previous action of silently
437 ignoring the error, but will still leave the file there. This
438 needs some kind of magic. */
439 if (r == EACCES)
440 return (fd2);
441 #endif /* __CYGWIN__ */
442 close (fd2);
443 free (filename);
444 errno = r;
445 return (-1);
446 }
447
448 free (filename);
449 return (fd2);
450 }
451
452 #define RF_DEVFD 1
453 #define RF_DEVSTDERR 2
454 #define RF_DEVSTDIN 3
455 #define RF_DEVSTDOUT 4
456 #define RF_DEVTCP 5
457 #define RF_DEVUDP 6
458
459 /* A list of pattern/value pairs for filenames that the redirection
460 code handles specially. */
461 static STRING_INT_ALIST _redir_special_filenames[] = {
462 #if !defined (HAVE_DEV_FD)
463 { "/dev/fd/[0-9]*", RF_DEVFD },
464 #endif
465 #if !defined (HAVE_DEV_STDIN)
466 { "/dev/stderr", RF_DEVSTDERR },
467 { "/dev/stdin", RF_DEVSTDIN },
468 { "/dev/stdout", RF_DEVSTDOUT },
469 #endif
470 #if defined (NETWORK_REDIRECTIONS)
471 { "/dev/tcp/*/*", RF_DEVTCP },
472 { "/dev/udp/*/*", RF_DEVUDP },
473 #endif
474 { (char *)NULL, -1 }
475 };
476
477 static int
478 redir_special_open (spec, filename, flags, mode, ri)
479 int spec;
480 char *filename;
481 int flags, mode;
482 enum r_instruction ri;
483 {
484 int fd;
485 #if !defined (HAVE_DEV_FD)
486 intmax_t lfd;
487 #endif
488
489 fd = -1;
490 switch (spec)
491 {
492 #if !defined (HAVE_DEV_FD)
493 case RF_DEVFD:
494 if (all_digits (filename+8) && legal_number (filename+8, &lfd) && lfd == (int)lfd)
495 {
496 fd = lfd;
497 fd = fcntl (fd, F_DUPFD, SHELL_FD_BASE);
498 }
499 else
500 fd = AMBIGUOUS_REDIRECT;
501 break;
502 #endif
503
504 #if !defined (HAVE_DEV_STDIN)
505 case RF_DEVSTDIN:
506 fd = fcntl (0, F_DUPFD, SHELL_FD_BASE);
507 break;
508 case RF_DEVSTDOUT:
509 fd = fcntl (1, F_DUPFD, SHELL_FD_BASE);
510 break;
511 case RF_DEVSTDERR:
512 fd = fcntl (2, F_DUPFD, SHELL_FD_BASE);
513 break;
514 #endif
515
516 #if defined (NETWORK_REDIRECTIONS)
517 case RF_DEVTCP:
518 case RF_DEVUDP:
519 #if defined (HAVE_NETWORK)
520 fd = netopen (filename);
521 #else
522 internal_warning (_("/dev/(tcp|udp)/host/port not supported without networking"));
523 fd = open (filename, flags, mode);
524 #endif
525 break;
526 #endif /* NETWORK_REDIRECTIONS */
527 }
528
529 return fd;
530 }
531
532 /* Open FILENAME with FLAGS in noclobber mode, hopefully avoiding most
533 race conditions and avoiding the problem where the file is replaced
534 between the stat(2) and open(2). */
535 static int
536 noclobber_open (filename, flags, mode, ri)
537 char *filename;
538 int flags, mode;
539 enum r_instruction ri;
540 {
541 int r, fd;
542 struct stat finfo, finfo2;
543
544 /* If the file exists and is a regular file, return an error
545 immediately. */
546 r = stat (filename, &finfo);
547 if (r == 0 && (S_ISREG (finfo.st_mode)))
548 return (NOCLOBBER_REDIRECT);
549
550 /* If the file was not present (r != 0), make sure we open it
551 exclusively so that if it is created before we open it, our open
552 will fail. Make sure that we do not truncate an existing file.
553 Note that we don't turn on O_EXCL unless the stat failed -- if
554 the file was not a regular file, we leave O_EXCL off. */
555 flags &= ~O_TRUNC;
556 if (r != 0)
557 {
558 fd = open (filename, flags|O_EXCL, mode);
559 return ((fd < 0 && errno == EEXIST) ? NOCLOBBER_REDIRECT : fd);
560 }
561 fd = open (filename, flags, mode);
562
563 /* If the open failed, return the file descriptor right away. */
564 if (fd < 0)
565 return (errno == EEXIST ? NOCLOBBER_REDIRECT : fd);
566
567 /* OK, the open succeeded, but the file may have been changed from a
568 non-regular file to a regular file between the stat and the open.
569 We are assuming that the O_EXCL open handles the case where FILENAME
570 did not exist and is symlinked to an existing file between the stat
571 and open. */
572
573 /* If we can open it and fstat the file descriptor, and neither check
574 revealed that it was a regular file, and the file has not been replaced,
575 return the file descriptor. */
576 if ((fstat (fd, &finfo2) == 0) && (S_ISREG (finfo2.st_mode) == 0) &&
577 r == 0 && (S_ISREG (finfo.st_mode) == 0) &&
578 same_file (filename, filename, &finfo, &finfo2))
579 return fd;
580
581 /* The file has been replaced. badness. */
582 close (fd);
583 errno = EEXIST;
584 return (NOCLOBBER_REDIRECT);
585 }
586
587 static int
588 redir_open (filename, flags, mode, ri)
589 char *filename;
590 int flags, mode;
591 enum r_instruction ri;
592 {
593 int fd, r;
594
595 r = find_string_in_alist (filename, _redir_special_filenames, 1);
596 if (r >= 0)
597 return (redir_special_open (r, filename, flags, mode, ri));
598
599 /* If we are in noclobber mode, you are not allowed to overwrite
600 existing files. Check before opening. */
601 if (noclobber && CLOBBERING_REDIRECT (ri))
602 {
603 fd = noclobber_open (filename, flags, mode, ri);
604 if (fd == NOCLOBBER_REDIRECT)
605 return (NOCLOBBER_REDIRECT);
606 }
607 else
608 {
609 fd = open (filename, flags, mode);
610 #if defined (AFS)
611 if ((fd < 0) && (errno == EACCES))
612 {
613 fd = open (filename, flags & ~O_CREAT, mode);
614 errno = EACCES; /* restore errno */
615 }
616 #endif /* AFS */
617 }
618
619 return fd;
620 }
621
622 static int
623 undoablefd (fd)
624 int fd;
625 {
626 int clexec;
627
628 clexec = fcntl (fd, F_GETFD, 0);
629 if (clexec == -1 || (fd >= SHELL_FD_BASE && clexec == 1))
630 return 0;
631 return 1;
632 }
633
634 /* Do the specific redirection requested. Returns errno or one of the
635 special redirection errors (*_REDIRECT) in case of error, 0 on success.
636 If flags & RX_ACTIVE is zero, then just do whatever is neccessary to
637 produce the appropriate side effects. flags & RX_UNDOABLE, if non-zero,
638 says to remember how to undo each redirection. If flags & RX_CLEXEC is
639 non-zero, then we set all file descriptors > 2 that we open to be
640 close-on-exec. */
641 static int
642 do_redirection_internal (redirect, flags)
643 REDIRECT *redirect;
644 int flags;
645 {
646 WORD_DESC *redirectee;
647 int redir_fd, fd, redirector, r, oflags;
648 intmax_t lfd;
649 char *redirectee_word;
650 enum r_instruction ri;
651 REDIRECT *new_redirect;
652
653 redirectee = redirect->redirectee.filename;
654 redir_fd = redirect->redirectee.dest;
655 redirector = redirect->redirector;
656 ri = redirect->instruction;
657
658 if (redirect->flags & RX_INTERNAL)
659 flags |= RX_INTERNAL;
660
661 if (TRANSLATE_REDIRECT (ri))
662 {
663 /* We have [N]>&WORD[-] or [N]<&WORD[-]. Expand WORD, then translate
664 the redirection into a new one and continue. */
665 redirectee_word = redirection_expand (redirectee);
666
667 /* XXX - what to do with [N]<&$w- where w is unset or null? ksh93
668 closes N. */
669 if (redirectee_word == 0)
670 return (AMBIGUOUS_REDIRECT);
671 else if (redirectee_word[0] == '-' && redirectee_word[1] == '\0')
672 {
673 rd.dest = 0;
674 new_redirect = make_redirection (redirector, r_close_this, rd);
675 }
676 else if (all_digits (redirectee_word))
677 {
678 if (legal_number (redirectee_word, &lfd) && (int)lfd == lfd)
679 rd.dest = lfd;
680 else
681 rd.dest = -1; /* XXX */
682 switch (ri)
683 {
684 case r_duplicating_input_word:
685 new_redirect = make_redirection (redirector, r_duplicating_input, rd);
686 break;
687 case r_duplicating_output_word:
688 new_redirect = make_redirection (redirector, r_duplicating_output, rd);
689 break;
690 case r_move_input_word:
691 new_redirect = make_redirection (redirector, r_move_input, rd);
692 break;
693 case r_move_output_word:
694 new_redirect = make_redirection (redirector, r_move_output, rd);
695 break;
696 }
697 }
698 else if (ri == r_duplicating_output_word && redirector == 1)
699 {
700 rd.filename = make_bare_word (redirectee_word);
701 new_redirect = make_redirection (1, r_err_and_out, rd);
702 }
703 else
704 {
705 free (redirectee_word);
706 return (AMBIGUOUS_REDIRECT);
707 }
708
709 free (redirectee_word);
710
711 /* Set up the variables needed by the rest of the function from the
712 new redirection. */
713 if (new_redirect->instruction == r_err_and_out)
714 {
715 char *alloca_hack;
716
717 /* Copy the word without allocating any memory that must be
718 explicitly freed. */
719 redirectee = (WORD_DESC *)alloca (sizeof (WORD_DESC));
720 xbcopy ((char *)new_redirect->redirectee.filename,
721 (char *)redirectee, sizeof (WORD_DESC));
722
723 alloca_hack = (char *)
724 alloca (1 + strlen (new_redirect->redirectee.filename->word));
725 redirectee->word = alloca_hack;
726 strcpy (redirectee->word, new_redirect->redirectee.filename->word);
727 }
728 else
729 /* It's guaranteed to be an integer, and shouldn't be freed. */
730 redirectee = new_redirect->redirectee.filename;
731
732 redir_fd = new_redirect->redirectee.dest;
733 redirector = new_redirect->redirector;
734 ri = new_redirect->instruction;
735
736 /* Overwrite the flags element of the old redirect with the new value. */
737 redirect->flags = new_redirect->flags;
738 dispose_redirects (new_redirect);
739 }
740
741 switch (ri)
742 {
743 case r_output_direction:
744 case r_appending_to:
745 case r_input_direction:
746 case r_inputa_direction:
747 case r_err_and_out: /* command &>filename */
748 case r_append_err_and_out: /* command &>> filename */
749 case r_input_output:
750 case r_output_force:
751 if (posixly_correct && interactive_shell == 0)
752 {
753 oflags = redirectee->flags;
754 redirectee->flags |= W_NOGLOB;
755 }
756 redirectee_word = redirection_expand (redirectee);
757 if (posixly_correct && interactive_shell == 0)
758 redirectee->flags = oflags;
759
760 if (redirectee_word == 0)
761 return (AMBIGUOUS_REDIRECT);
762
763 #if defined (RESTRICTED_SHELL)
764 if (restricted && (WRITE_REDIRECT (ri)))
765 {
766 free (redirectee_word);
767 return (RESTRICTED_REDIRECT);
768 }
769 #endif /* RESTRICTED_SHELL */
770
771 fd = redir_open (redirectee_word, redirect->flags, 0666, ri);
772 free (redirectee_word);
773
774 if (fd == NOCLOBBER_REDIRECT)
775 return (fd);
776
777 if (fd < 0)
778 return (errno);
779
780 if (flags & RX_ACTIVE)
781 {
782 if (flags & RX_UNDOABLE)
783 {
784 /* Only setup to undo it if the thing to undo is active. */
785 if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
786 add_undo_redirect (redirector, ri, -1);
787 else
788 add_undo_close_redirect (redirector);
789 }
790
791 #if defined (BUFFERED_INPUT)
792 check_bash_input (redirector);
793 #endif
794
795 /* Make sure there is no pending output before we change the state
796 of the underlying file descriptor, since the builtins use stdio
797 for output. */
798 if (redirector == 1 && fileno (stdout) == redirector)
799 {
800 fflush (stdout);
801 fpurge (stdout);
802 }
803 else if (redirector == 2 && fileno (stderr) == redirector)
804 {
805 fflush (stderr);
806 fpurge (stderr);
807 }
808
809 if ((fd != redirector) && (dup2 (fd, redirector) < 0))
810 return (errno);
811
812 #if defined (BUFFERED_INPUT)
813 /* Do not change the buffered stream for an implicit redirection
814 of /dev/null to fd 0 for asynchronous commands without job
815 control (r_inputa_direction). */
816 if (ri == r_input_direction || ri == r_input_output)
817 duplicate_buffered_stream (fd, redirector);
818 #endif /* BUFFERED_INPUT */
819
820 /*
821 * If we're remembering, then this is the result of a while, for
822 * or until loop with a loop redirection, or a function/builtin
823 * executing in the parent shell with a redirection. In the
824 * function/builtin case, we want to set all file descriptors > 2
825 * to be close-on-exec to duplicate the effect of the old
826 * for i = 3 to NOFILE close(i) loop. In the case of the loops,
827 * both sh and ksh leave the file descriptors open across execs.
828 * The Posix standard mentions only the exec builtin.
829 */
830 if ((flags & RX_CLEXEC) && (redirector > 2))
831 SET_CLOSE_ON_EXEC (redirector);
832 }
833
834 if (fd != redirector)
835 {
836 #if defined (BUFFERED_INPUT)
837 if (INPUT_REDIRECT (ri))
838 close_buffered_fd (fd);
839 else
840 #endif /* !BUFFERED_INPUT */
841 close (fd); /* Don't close what we just opened! */
842 }
843
844 /* If we are hacking both stdout and stderr, do the stderr
845 redirection here. */
846 if (ri == r_err_and_out || ri == r_append_err_and_out)
847 {
848 if (flags & RX_ACTIVE)
849 {
850 if (flags & RX_UNDOABLE)
851 add_undo_redirect (2, ri, -1);
852 if (dup2 (1, 2) < 0)
853 return (errno);
854 }
855 }
856 break;
857
858 case r_reading_until:
859 case r_deblank_reading_until:
860 case r_reading_string:
861 /* REDIRECTEE is a pointer to a WORD_DESC containing the text of
862 the new input. Place it in a temporary file. */
863 if (redirectee)
864 {
865 fd = here_document_to_fd (redirectee, ri);
866
867 if (fd < 0)
868 {
869 heredoc_errno = errno;
870 return (HEREDOC_REDIRECT);
871 }
872
873 if (flags & RX_ACTIVE)
874 {
875 if (flags & RX_UNDOABLE)
876 {
877 /* Only setup to undo it if the thing to undo is active. */
878 if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
879 add_undo_redirect (redirector, ri, -1);
880 else
881 add_undo_close_redirect (redirector);
882 }
883
884 #if defined (BUFFERED_INPUT)
885 check_bash_input (redirector);
886 #endif
887 if (fd != redirector && dup2 (fd, redirector) < 0)
888 {
889 r = errno;
890 close (fd);
891 return (r);
892 }
893
894 #if defined (BUFFERED_INPUT)
895 duplicate_buffered_stream (fd, redirector);
896 #endif
897
898 if ((flags & RX_CLEXEC) && (redirector > 2))
899 SET_CLOSE_ON_EXEC (redirector);
900 }
901
902 if (fd != redirector)
903 #if defined (BUFFERED_INPUT)
904 close_buffered_fd (fd);
905 #else
906 close (fd);
907 #endif
908 }
909 break;
910
911 case r_duplicating_input:
912 case r_duplicating_output:
913 case r_move_input:
914 case r_move_output:
915 if ((flags & RX_ACTIVE) && (redir_fd != redirector))
916 {
917 if (flags & RX_UNDOABLE)
918 {
919 /* Only setup to undo it if the thing to undo is active. */
920 if (fcntl (redirector, F_GETFD, 0) != -1)
921 add_undo_redirect (redirector, ri, redir_fd);
922 else
923 add_undo_close_redirect (redirector);
924 }
925 #if defined (BUFFERED_INPUT)
926 check_bash_input (redirector);
927 #endif
928 /* This is correct. 2>&1 means dup2 (1, 2); */
929 if (dup2 (redir_fd, redirector) < 0)
930 return (errno);
931
932 #if defined (BUFFERED_INPUT)
933 if (ri == r_duplicating_input || ri == r_move_input)
934 duplicate_buffered_stream (redir_fd, redirector);
935 #endif /* BUFFERED_INPUT */
936
937 /* First duplicate the close-on-exec state of redirectee. dup2
938 leaves the flag unset on the new descriptor, which means it
939 stays open. Only set the close-on-exec bit for file descriptors
940 greater than 2 in any case, since 0-2 should always be open
941 unless closed by something like `exec 2<&-'. It should always
942 be safe to set fds > 2 to close-on-exec if they're being used to
943 save file descriptors < 2, since we don't need to preserve the
944 state of the close-on-exec flag for those fds -- they should
945 always be open. */
946 /* if ((already_set || set_unconditionally) && (ok_to_set))
947 set_it () */
948 #if 0
949 if (((fcntl (redir_fd, F_GETFD, 0) == 1) || redir_fd < 2 || (flags & RX_CLEXEC)) &&
950 (redirector > 2))
951 #else
952 if (((fcntl (redir_fd, F_GETFD, 0) == 1) || (redir_fd < 2 && (flags & RX_INTERNAL)) || (flags & RX_CLEXEC)) &&
953 (redirector > 2))
954 #endif
955 SET_CLOSE_ON_EXEC (redirector);
956
957 /* When undoing saving of non-standard file descriptors (>=3) using
958 file descriptors >= SHELL_FD_BASE, we set the saving fd to be
959 close-on-exec and use a flag to decide how to set close-on-exec
960 when the fd is restored. */
961 if ((redirect->flags & RX_INTERNAL) && (redirect->flags & RX_SAVCLEXEC) && redirector >= 3 && redir_fd >= SHELL_FD_BASE)
962 SET_OPEN_ON_EXEC (redirector);
963
964 /* dup-and-close redirection */
965 if (ri == r_move_input || ri == r_move_output)
966 {
967 close (redir_fd);
968 #if defined (COPROCESS_SUPPORT)
969 coproc_fdchk (redir_fd); /* XXX - loses coproc fds */
970 #endif
971 }
972 }
973 break;
974
975 case r_close_this:
976 if (flags & RX_ACTIVE)
977 {
978 if ((flags & RX_UNDOABLE) && (fcntl (redirector, F_GETFD, 0) != -1))
979 add_undo_redirect (redirector, ri, -1);
980
981 #if defined (COPROCESS_SUPPORT)
982 coproc_fdchk (redirector);
983 #endif
984
985 #if defined (BUFFERED_INPUT)
986 check_bash_input (redirector);
987 close_buffered_fd (redirector);
988 #else /* !BUFFERED_INPUT */
989 close (redirector);
990 #endif /* !BUFFERED_INPUT */
991 }
992 break;
993
994 case r_duplicating_input_word:
995 case r_duplicating_output_word:
996 break;
997 }
998 return (0);
999 }
1000
1001 /* Remember the file descriptor associated with the slot FD,
1002 on REDIRECTION_UNDO_LIST. Note that the list will be reversed
1003 before it is executed. Any redirections that need to be undone
1004 even if REDIRECTION_UNDO_LIST is discarded by the exec builtin
1005 are also saved on EXEC_REDIRECTION_UNDO_LIST. FDBASE says where to
1006 start the duplicating. If it's less than SHELL_FD_BASE, we're ok,
1007 and can use SHELL_FD_BASE (-1 == don't care). If it's >= SHELL_FD_BASE,
1008 we have to make sure we don't use fdbase to save a file descriptor,
1009 since we're going to use it later (e.g., make sure we don't save fd 0
1010 to fd 10 if we have a redirection like 0<&10). If the value of fdbase
1011 puts the process over its fd limit, causing fcntl to fail, we try
1012 again with SHELL_FD_BASE. */
1013 static int
1014 add_undo_redirect (fd, ri, fdbase)
1015 int fd;
1016 enum r_instruction ri;
1017 int fdbase;
1018 {
1019 int new_fd, clexec_flag;
1020 REDIRECT *new_redirect, *closer, *dummy_redirect;
1021
1022 new_fd = fcntl (fd, F_DUPFD, (fdbase < SHELL_FD_BASE) ? SHELL_FD_BASE : fdbase+1);
1023 if (new_fd < 0)
1024 new_fd = fcntl (fd, F_DUPFD, SHELL_FD_BASE);
1025
1026 if (new_fd < 0)
1027 {
1028 sys_error (_("redirection error: cannot duplicate fd"));
1029 return (-1);
1030 }
1031
1032 clexec_flag = fcntl (fd, F_GETFD, 0);
1033
1034 rd.dest = 0;
1035 closer = make_redirection (new_fd, r_close_this, rd);
1036 closer->flags |= RX_INTERNAL;
1037 dummy_redirect = copy_redirects (closer);
1038
1039 rd.dest = new_fd;
1040 if (fd == 0)
1041 new_redirect = make_redirection (fd, r_duplicating_input, rd);
1042 else
1043 new_redirect = make_redirection (fd, r_duplicating_output, rd);
1044 new_redirect->flags |= RX_INTERNAL;
1045 if (clexec_flag == 0 && fd >= 3 && new_fd >= SHELL_FD_BASE)
1046 new_redirect->flags |= RX_SAVCLEXEC;
1047 new_redirect->next = closer;
1048
1049 closer->next = redirection_undo_list;
1050 redirection_undo_list = new_redirect;
1051
1052 /* Save redirections that need to be undone even if the undo list
1053 is thrown away by the `exec' builtin. */
1054 add_exec_redirect (dummy_redirect);
1055
1056 /* experimental: if we're saving a redirection to undo for a file descriptor
1057 above SHELL_FD_BASE, add a redirection to be undone if the exec builtin
1058 causes redirections to be discarded. There needs to be a difference
1059 between fds that are used to save other fds and then are the target of
1060 user redirctions and fds that are just the target of user redirections.
1061 We use the close-on-exec flag to tell the difference; fds > SHELL_FD_BASE
1062 that have the close-on-exec flag set are assumed to be fds used internally
1063 to save others. */
1064 if (fd >= SHELL_FD_BASE && ri != r_close_this && clexec_flag)
1065 {
1066 rd.dest = new_fd;
1067 new_redirect = make_redirection (fd, r_duplicating_output, rd);
1068 new_redirect->flags |= RX_INTERNAL;
1069
1070 add_exec_redirect (new_redirect);
1071 }
1072
1073 /* File descriptors used only for saving others should always be
1074 marked close-on-exec. Unfortunately, we have to preserve the
1075 close-on-exec state of the file descriptor we are saving, since
1076 fcntl (F_DUPFD) sets the new file descriptor to remain open
1077 across execs. If, however, the file descriptor whose state we
1078 are saving is <= 2, we can just set the close-on-exec flag,
1079 because file descriptors 0-2 should always be open-on-exec,
1080 and the restore above in do_redirection() will take care of it. */
1081 if (clexec_flag || fd < 3)
1082 SET_CLOSE_ON_EXEC (new_fd);
1083 else if (redirection_undo_list->flags & RX_SAVCLEXEC)
1084 SET_CLOSE_ON_EXEC (new_fd);
1085
1086 return (0);
1087 }
1088
1089 /* Set up to close FD when we are finished with the current command
1090 and its redirections. */
1091 static void
1092 add_undo_close_redirect (fd)
1093 int fd;
1094 {
1095 REDIRECT *closer;
1096
1097 rd.dest = 0;
1098 closer = make_redirection (fd, r_close_this, rd);
1099 closer->flags |= RX_INTERNAL;
1100 closer->next = redirection_undo_list;
1101 redirection_undo_list = closer;
1102 }
1103
1104 static void
1105 add_exec_redirect (dummy_redirect)
1106 REDIRECT *dummy_redirect;
1107 {
1108 dummy_redirect->next = exec_redirection_undo_list;
1109 exec_redirection_undo_list = dummy_redirect;
1110 }
1111
1112 /* Return 1 if the redirection specified by RI and REDIRECTOR alters the
1113 standard input. */
1114 static int
1115 stdin_redirection (ri, redirector)
1116 enum r_instruction ri;
1117 int redirector;
1118 {
1119 switch (ri)
1120 {
1121 case r_input_direction:
1122 case r_inputa_direction:
1123 case r_input_output:
1124 case r_reading_until:
1125 case r_deblank_reading_until:
1126 case r_reading_string:
1127 return (1);
1128 case r_duplicating_input:
1129 case r_duplicating_input_word:
1130 case r_close_this:
1131 return (redirector == 0);
1132 case r_output_direction:
1133 case r_appending_to:
1134 case r_duplicating_output:
1135 case r_err_and_out:
1136 case r_append_err_and_out:
1137 case r_output_force:
1138 case r_duplicating_output_word:
1139 return (0);
1140 }
1141 return (0);
1142 }
1143
1144 /* Return non-zero if any of the redirections in REDIRS alter the standard
1145 input. */
1146 int
1147 stdin_redirects (redirs)
1148 REDIRECT *redirs;
1149 {
1150 REDIRECT *rp;
1151 int n;
1152
1153 for (n = 0, rp = redirs; rp; rp = rp->next)
1154 n += stdin_redirection (rp->instruction, rp->redirector);
1155 return n;
1156 }