]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - bin/sh/redir.c
MFC r363988:
[FreeBSD/stable/9.git] / bin / sh / redir.c
1 /*-
2  * Copyright (c) 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)redir.c     8.2 (Berkeley) 5/4/95";
36 #endif
37 #endif /* not lint */
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <signal.h>
44 #include <string.h>
45 #include <fcntl.h>
46 #include <errno.h>
47 #include <unistd.h>
48 #include <stdlib.h>
49
50 /*
51  * Code for dealing with input/output redirection.
52  */
53
54 #include "shell.h"
55 #include "nodes.h"
56 #include "jobs.h"
57 #include "expand.h"
58 #include "redir.h"
59 #include "output.h"
60 #include "memalloc.h"
61 #include "error.h"
62 #include "options.h"
63
64
65 #define EMPTY -2                /* marks an unused slot in redirtab */
66 #define CLOSED -1               /* fd was not open before redir */
67 #define PIPESIZE 4096           /* amount of buffering in a pipe */
68
69
70 MKINIT
71 struct redirtab {
72         struct redirtab *next;
73         int renamed[10];
74 };
75
76
77 MKINIT struct redirtab *redirlist;
78
79 /*
80  * We keep track of whether or not fd0 has been redirected.  This is for
81  * background commands, where we want to redirect fd0 to /dev/null only
82  * if it hasn't already been redirected.
83 */
84 static int fd0_redirected = 0;
85
86 static void openredirect(union node *, char[10 ]);
87 static int openhere(union node *);
88
89
90 /*
91  * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
92  * old file descriptors are stashed away so that the redirection can be
93  * undone by calling popredir.  If the REDIR_BACKQ flag is set, then the
94  * standard output, and the standard error if it becomes a duplicate of
95  * stdout, is saved in memory.
96 *
97  * We suppress interrupts so that we won't leave open file
98  * descriptors around.  Because the signal handler remains
99  * installed and we do not use system call restart, interrupts
100  * will still abort blocking opens such as fifos (they will fail
101  * with EINTR). There is, however, a race condition if an interrupt
102  * arrives after INTOFF and before open blocks.
103  */
104
105 void
106 redirect(union node *redir, int flags)
107 {
108         union node *n;
109         struct redirtab *sv = NULL;
110         int i;
111         int fd;
112         char memory[10];        /* file descriptors to write to memory */
113
114         INTOFF;
115         for (i = 10 ; --i >= 0 ; )
116                 memory[i] = 0;
117         memory[1] = flags & REDIR_BACKQ;
118         if (flags & REDIR_PUSH) {
119                 sv = ckmalloc(sizeof (struct redirtab));
120                 for (i = 0 ; i < 10 ; i++)
121                         sv->renamed[i] = EMPTY;
122                 sv->next = redirlist;
123                 redirlist = sv;
124         }
125         for (n = redir ; n ; n = n->nfile.next) {
126                 fd = n->nfile.fd;
127                 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
128                     n->ndup.dupfd == fd)
129                         continue; /* redirect from/to same file descriptor */
130
131                 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
132                         INTOFF;
133                         if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
134                                 switch (errno) {
135                                 case EBADF:
136                                         i = CLOSED;
137                                         break;
138                                 default:
139                                         INTON;
140                                         error("%d: %s", fd, strerror(errno));
141                                         break;
142                                 }
143                         } else
144                                 (void)fcntl(i, F_SETFD, FD_CLOEXEC);
145                         sv->renamed[fd] = i;
146                         INTON;
147                 }
148                 if (fd == 0)
149                         fd0_redirected++;
150                 openredirect(n, memory);
151                 INTON;
152                 INTOFF;
153         }
154         if (memory[1])
155                 out1 = &memout;
156         if (memory[2])
157                 out2 = &memout;
158         INTON;
159 }
160
161
162 static void
163 openredirect(union node *redir, char memory[10])
164 {
165         struct stat sb;
166         int fd = redir->nfile.fd;
167         char *fname;
168         int f;
169         int e;
170
171         memory[fd] = 0;
172         switch (redir->nfile.type) {
173         case NFROM:
174                 fname = redir->nfile.expfname;
175                 if ((f = open(fname, O_RDONLY)) < 0)
176                         error("cannot open %s: %s", fname, strerror(errno));
177 movefd:
178                 if (f != fd) {
179                         if (dup2(f, fd) == -1) {
180                                 e = errno;
181                                 close(f);
182                                 error("%d: %s", fd, strerror(e));
183                         }
184                         close(f);
185                 }
186                 break;
187         case NFROMTO:
188                 fname = redir->nfile.expfname;
189                 if ((f = open(fname, O_RDWR|O_CREAT, 0666)) < 0)
190                         error("cannot create %s: %s", fname, strerror(errno));
191                 goto movefd;
192         case NTO:
193                 if (Cflag) {
194                         fname = redir->nfile.expfname;
195                         if (stat(fname, &sb) == -1) {
196                                 if ((f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666)) < 0)
197                                         error("cannot create %s: %s", fname, strerror(errno));
198                         } else if (!S_ISREG(sb.st_mode)) {
199                                 if ((f = open(fname, O_WRONLY, 0666)) < 0)
200                                         error("cannot create %s: %s", fname, strerror(errno));
201                                 if (fstat(f, &sb) != -1 && S_ISREG(sb.st_mode)) {
202                                         close(f);
203                                         error("cannot create %s: %s", fname,
204                                             strerror(EEXIST));
205                                 }
206                         } else
207                                 error("cannot create %s: %s", fname,
208                                     strerror(EEXIST));
209                         goto movefd;
210                 }
211                 /* FALLTHROUGH */
212         case NCLOBBER:
213                 fname = redir->nfile.expfname;
214                 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
215                         error("cannot create %s: %s", fname, strerror(errno));
216                 goto movefd;
217         case NAPPEND:
218                 fname = redir->nfile.expfname;
219                 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
220                         error("cannot create %s: %s", fname, strerror(errno));
221                 goto movefd;
222         case NTOFD:
223         case NFROMFD:
224                 if (redir->ndup.dupfd >= 0) {   /* if not ">&-" */
225                         if (memory[redir->ndup.dupfd])
226                                 memory[fd] = 1;
227                         else {
228                                 if (dup2(redir->ndup.dupfd, fd) < 0)
229                                         error("%d: %s", redir->ndup.dupfd,
230                                                         strerror(errno));
231                         }
232                 } else {
233                         close(fd);
234                 }
235                 break;
236         case NHERE:
237         case NXHERE:
238                 f = openhere(redir);
239                 goto movefd;
240         default:
241                 abort();
242         }
243 }
244
245
246 /*
247  * Handle here documents.  Normally we fork off a process to write the
248  * data to a pipe.  If the document is short, we can stuff the data in
249  * the pipe without forking.
250  */
251
252 static int
253 openhere(union node *redir)
254 {
255         int pip[2];
256         int len = 0;
257
258         if (pipe(pip) < 0)
259                 error("Pipe call failed: %s", strerror(errno));
260         if (redir->type == NHERE) {
261                 len = strlen(redir->nhere.doc->narg.text);
262                 if (len <= PIPESIZE) {
263                         xwrite(pip[1], redir->nhere.doc->narg.text, len);
264                         goto out;
265                 }
266         }
267         if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
268                 close(pip[0]);
269                 signal(SIGINT, SIG_IGN);
270                 signal(SIGQUIT, SIG_IGN);
271                 signal(SIGHUP, SIG_IGN);
272                 signal(SIGTSTP, SIG_IGN);
273                 signal(SIGPIPE, SIG_DFL);
274                 if (redir->type == NHERE)
275                         xwrite(pip[1], redir->nhere.doc->narg.text, len);
276                 else
277                         expandhere(redir->nhere.doc, pip[1]);
278                 _exit(0);
279         }
280 out:
281         close(pip[1]);
282         return pip[0];
283 }
284
285
286
287 /*
288  * Undo the effects of the last redirection.
289  */
290
291 void
292 popredir(void)
293 {
294         struct redirtab *rp = redirlist;
295         int i;
296
297         for (i = 0 ; i < 10 ; i++) {
298                 if (rp->renamed[i] != EMPTY) {
299                         if (i == 0)
300                                 fd0_redirected--;
301                         if (rp->renamed[i] >= 0) {
302                                 dup2(rp->renamed[i], i);
303                                 close(rp->renamed[i]);
304                         } else {
305                                 close(i);
306                         }
307                 }
308         }
309         INTOFF;
310         redirlist = rp->next;
311         ckfree(rp);
312         INTON;
313 }
314
315 /*
316  * Undo all redirections.  Called on error or interrupt.
317  */
318
319 #ifdef mkinit
320
321 INCLUDE "redir.h"
322
323 RESET {
324         while (redirlist)
325                 popredir();
326 }
327
328 #endif
329
330 /* Return true if fd 0 has already been redirected at least once.  */
331 int
332 fd0_redirected_p(void)
333 {
334         return fd0_redirected != 0;
335 }
336
337 /*
338  * Discard all saved file descriptors.
339  */
340
341 void
342 clearredir(void)
343 {
344         struct redirtab *rp;
345         int i;
346
347         for (rp = redirlist ; rp ; rp = rp->next) {
348                 for (i = 0 ; i < 10 ; i++) {
349                         if (rp->renamed[i] >= 0) {
350                                 close(rp->renamed[i]);
351                         }
352                         rp->renamed[i] = EMPTY;
353                 }
354         }
355 }