]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - bin/sh/redir.c
Merge ACPICA 20101209.
[FreeBSD/FreeBSD.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
98 void
99 redirect(union node *redir, int flags)
100 {
101         union node *n;
102         struct redirtab *sv = NULL;
103         int i;
104         int fd;
105         char memory[10];        /* file descriptors to write to memory */
106
107         for (i = 10 ; --i >= 0 ; )
108                 memory[i] = 0;
109         memory[1] = flags & REDIR_BACKQ;
110         if (flags & REDIR_PUSH) {
111                 sv = ckmalloc(sizeof (struct redirtab));
112                 for (i = 0 ; i < 10 ; i++)
113                         sv->renamed[i] = EMPTY;
114                 sv->next = redirlist;
115                 redirlist = sv;
116         }
117         for (n = redir ; n ; n = n->nfile.next) {
118                 fd = n->nfile.fd;
119                 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
120                     n->ndup.dupfd == fd)
121                         continue; /* redirect from/to same file descriptor */
122
123                 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
124                         INTOFF;
125                         if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
126                                 switch (errno) {
127                                 case EBADF:
128                                         i = CLOSED;
129                                         break;
130                                 default:
131                                         INTON;
132                                         error("%d: %s", fd, strerror(errno));
133                                         break;
134                                 }
135                         } else
136                                 (void)fcntl(i, F_SETFD, FD_CLOEXEC);
137                         sv->renamed[fd] = i;
138                         INTON;
139                 }
140                 if (fd == 0)
141                         fd0_redirected++;
142                 openredirect(n, memory);
143         }
144         if (memory[1])
145                 out1 = &memout;
146         if (memory[2])
147                 out2 = &memout;
148 }
149
150
151 static void
152 openredirect(union node *redir, char memory[10])
153 {
154         struct stat sb;
155         int fd = redir->nfile.fd;
156         char *fname;
157         int f;
158
159         /*
160          * We suppress interrupts so that we won't leave open file
161          * descriptors around.  Because the signal handler remains
162          * installed and we do not use system call restart, interrupts
163          * will still abort blocking opens such as fifos (they will fail
164          * with EINTR). There is, however, a race condition if an interrupt
165          * arrives after INTOFF and before open blocks.
166          */
167         INTOFF;
168         memory[fd] = 0;
169         switch (redir->nfile.type) {
170         case NFROM:
171                 fname = redir->nfile.expfname;
172                 if ((f = open(fname, O_RDONLY)) < 0)
173                         error("cannot open %s: %s", fname, strerror(errno));
174 movefd:
175                 if (f != fd) {
176                         dup2(f, fd);
177                         close(f);
178                 }
179                 break;
180         case NFROMTO:
181                 fname = redir->nfile.expfname;
182                 if ((f = open(fname, O_RDWR|O_CREAT, 0666)) < 0)
183                         error("cannot create %s: %s", fname, strerror(errno));
184                 goto movefd;
185         case NTO:
186                 if (Cflag) {
187                         fname = redir->nfile.expfname;
188                         if (stat(fname, &sb) == -1) {
189                                 if ((f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666)) < 0)
190                                         error("cannot create %s: %s", fname, strerror(errno));
191                         } else if (!S_ISREG(sb.st_mode)) {
192                                 if ((f = open(fname, O_WRONLY, 0666)) < 0)
193                                         error("cannot create %s: %s", fname, strerror(errno));
194                                 if (fstat(f, &sb) != -1 && S_ISREG(sb.st_mode)) {
195                                         close(f);
196                                         error("cannot create %s: %s", fname,
197                                             strerror(EEXIST));
198                                 }
199                         } else
200                                 error("cannot create %s: %s", fname,
201                                     strerror(EEXIST));
202                         goto movefd;
203                 }
204                 /* FALLTHROUGH */
205         case NCLOBBER:
206                 fname = redir->nfile.expfname;
207                 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
208                         error("cannot create %s: %s", fname, strerror(errno));
209                 goto movefd;
210         case NAPPEND:
211                 fname = redir->nfile.expfname;
212                 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
213                         error("cannot create %s: %s", fname, strerror(errno));
214                 goto movefd;
215         case NTOFD:
216         case NFROMFD:
217                 if (redir->ndup.dupfd >= 0) {   /* if not ">&-" */
218                         if (memory[redir->ndup.dupfd])
219                                 memory[fd] = 1;
220                         else {
221                                 if (dup2(redir->ndup.dupfd, fd) < 0)
222                                         error("%d: %s", redir->ndup.dupfd,
223                                                         strerror(errno));
224                         }
225                 } else {
226                         close(fd);
227                 }
228                 break;
229         case NHERE:
230         case NXHERE:
231                 f = openhere(redir);
232                 goto movefd;
233         default:
234                 abort();
235         }
236         INTON;
237 }
238
239
240 /*
241  * Handle here documents.  Normally we fork off a process to write the
242  * data to a pipe.  If the document is short, we can stuff the data in
243  * the pipe without forking.
244  */
245
246 static int
247 openhere(union node *redir)
248 {
249         int pip[2];
250         int len = 0;
251
252         if (pipe(pip) < 0)
253                 error("Pipe call failed: %s", strerror(errno));
254         if (redir->type == NHERE) {
255                 len = strlen(redir->nhere.doc->narg.text);
256                 if (len <= PIPESIZE) {
257                         xwrite(pip[1], redir->nhere.doc->narg.text, len);
258                         goto out;
259                 }
260         }
261         if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
262                 close(pip[0]);
263                 signal(SIGINT, SIG_IGN);
264                 signal(SIGQUIT, SIG_IGN);
265                 signal(SIGHUP, SIG_IGN);
266                 signal(SIGTSTP, SIG_IGN);
267                 signal(SIGPIPE, SIG_DFL);
268                 if (redir->type == NHERE)
269                         xwrite(pip[1], redir->nhere.doc->narg.text, len);
270                 else
271                         expandhere(redir->nhere.doc, pip[1]);
272                 _exit(0);
273         }
274 out:
275         close(pip[1]);
276         return pip[0];
277 }
278
279
280
281 /*
282  * Undo the effects of the last redirection.
283  */
284
285 void
286 popredir(void)
287 {
288         struct redirtab *rp = redirlist;
289         int i;
290
291         for (i = 0 ; i < 10 ; i++) {
292                 if (rp->renamed[i] != EMPTY) {
293                         if (i == 0)
294                                 fd0_redirected--;
295                         if (rp->renamed[i] >= 0) {
296                                 dup2(rp->renamed[i], i);
297                                 close(rp->renamed[i]);
298                         } else {
299                                 close(i);
300                         }
301                 }
302         }
303         INTOFF;
304         redirlist = rp->next;
305         ckfree(rp);
306         INTON;
307 }
308
309 /*
310  * Undo all redirections.  Called on error or interrupt.
311  */
312
313 #ifdef mkinit
314
315 INCLUDE "redir.h"
316
317 RESET {
318         while (redirlist)
319                 popredir();
320 }
321
322 SHELLPROC {
323         clearredir();
324 }
325
326 #endif
327
328 /* Return true if fd 0 has already been redirected at least once.  */
329 int
330 fd0_redirected_p(void)
331 {
332         return fd0_redirected != 0;
333 }
334
335 /*
336  * Discard all saved file descriptors.
337  */
338
339 void
340 clearredir(void)
341 {
342         struct redirtab *rp;
343         int i;
344
345         for (rp = redirlist ; rp ; rp = rp->next) {
346                 for (i = 0 ; i < 10 ; i++) {
347                         if (rp->renamed[i] >= 0) {
348                                 close(rp->renamed[i]);
349                         }
350                         rp->renamed[i] = EMPTY;
351                 }
352         }
353 }