Use -s to flag POSIX's "special built-in" utilities in builtins.def. Add a
[dragonfly.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  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * @(#)redir.c  8.2 (Berkeley) 5/4/95
37  * $FreeBSD: src/bin/sh/redir.c,v 1.12.2.4 2002/08/27 01:36:28 tjr Exp $
38  * $DragonFly: src/bin/sh/redir.c,v 1.4 2007/01/06 03:44:04 pavalos Exp $
39  */
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 PIPESIZE 4096           /* amount of buffering in a pipe */
67
68
69 MKINIT
70 struct redirtab {
71         struct redirtab *next;
72         int renamed[10];
73 };
74
75
76 MKINIT struct redirtab *redirlist;
77
78 /*
79  * We keep track of whether or not fd0 has been redirected.  This is for
80  * background commands, where we want to redirect fd0 to /dev/null only
81  * if it hasn't already been redirected.
82 */
83 STATIC int fd0_redirected = 0;
84
85 STATIC void openredirect(union node *, char[10 ]);
86 STATIC int openhere(union node *);
87
88
89 /*
90  * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
91  * old file descriptors are stashed away so that the redirection can be
92  * undone by calling popredir.  If the REDIR_BACKQ flag is set, then the
93  * standard output, and the standard error if it becomes a duplicate of
94  * stdout, is saved in memory.
95  */
96
97 void
98 redirect(union node *redir, int flags)
99 {
100         union node *n;
101         struct redirtab *sv = NULL;
102         int i;
103         int fd;
104         int try;
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                 try = 0;
120                 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
121                     n->ndup.dupfd == fd)
122                         continue; /* redirect from/to same file descriptor */
123
124                 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
125                         INTOFF;
126 again:
127                         if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
128                                 switch (errno) {
129                                 case EBADF:
130                                         if (!try) {
131                                                 openredirect(n, memory);
132                                                 try++;
133                                                 goto again;
134                                         }
135                                         /* FALLTHROUGH*/
136                                 default:
137                                         INTON;
138                                         error("%d: %s", fd, strerror(errno));
139                                         break;
140                                 }
141                         }
142                         if (!try) {
143                                 sv->renamed[fd] = i;
144                         }
145                         INTON;
146                 }
147                 if (fd == 0)
148                         fd0_redirected++;
149                 if (!try)
150                         openredirect(n, memory);
151         }
152         if (memory[1])
153                 out1 = &memout;
154         if (memory[2])
155                 out2 = &memout;
156 }
157
158
159 STATIC void
160 openredirect(union node *redir, char memory[10])
161 {
162         struct stat sb;
163         int fd = redir->nfile.fd;
164         char *fname;
165         int f;
166
167         /*
168          * We suppress interrupts so that we won't leave open file
169          * descriptors around.  This may not be such a good idea because
170          * an open of a device or a fifo can block indefinitely.
171          */
172         INTOFF;
173         memory[fd] = 0;
174         switch (redir->nfile.type) {
175         case NFROM:
176                 fname = redir->nfile.expfname;
177                 if ((f = open(fname, O_RDONLY)) < 0)
178                         error("cannot open %s: %s", fname, strerror(errno));
179 movefd:
180                 if (f != fd) {
181                         close(fd);
182                         copyfd(f, fd);
183                         close(f);
184                 }
185                 break;
186         case NFROMTO:
187                 fname = redir->nfile.expfname;
188                 if ((f = open(fname, O_RDWR|O_CREAT, 0666)) < 0)
189                         error("cannot create %s: %s", fname, strerror(errno));
190                 goto movefd;
191         case NTO:
192                 fname = redir->nfile.expfname;
193                 if (Cflag && stat(fname, &sb) != -1 && S_ISREG(sb.st_mode))
194                         error("cannot create %s: %s", fname,
195                             strerror(EEXIST));
196                 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
197                         error("cannot create %s: %s", fname, strerror(errno));
198                 goto movefd;
199         case NCLOBBER:
200                 fname = redir->nfile.expfname;
201                 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
202                         error("cannot create %s: %s", fname, strerror(errno));
203                 goto movefd;
204         case NAPPEND:
205                 fname = redir->nfile.expfname;
206                 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
207                         error("cannot create %s: %s", fname, strerror(errno));
208                 goto movefd;
209         case NTOFD:
210         case NFROMFD:
211                 if (redir->ndup.dupfd >= 0) {   /* if not ">&-" */
212                         if (memory[redir->ndup.dupfd])
213                                 memory[fd] = 1;
214                         else {
215                                 close(fd);
216                                 copyfd(redir->ndup.dupfd, fd);
217                         }
218                 } else
219                         close(fd);
220                 break;
221         case NHERE:
222         case NXHERE:
223                 f = openhere(redir);
224                 goto movefd;
225         default:
226                 abort();
227         }
228         INTON;
229 }
230
231
232 /*
233  * Handle here documents.  Normally we fork off a process to write the
234  * data to a pipe.  If the document is short, we can stuff the data in
235  * the pipe without forking.
236  */
237
238 STATIC int
239 openhere(union node *redir)
240 {
241         int pip[2];
242         int len = 0;
243
244         if (pipe(pip) < 0)
245                 error("Pipe call failed: %s", strerror(errno));
246         if (redir->type == NHERE) {
247                 len = strlen(redir->nhere.doc->narg.text);
248                 if (len <= PIPESIZE) {
249                         xwrite(pip[1], redir->nhere.doc->narg.text, len);
250                         goto out;
251                 }
252         }
253         if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
254                 close(pip[0]);
255                 signal(SIGINT, SIG_IGN);
256                 signal(SIGQUIT, SIG_IGN);
257                 signal(SIGHUP, SIG_IGN);
258                 signal(SIGTSTP, SIG_IGN);
259                 signal(SIGPIPE, SIG_DFL);
260                 if (redir->type == NHERE)
261                         xwrite(pip[1], redir->nhere.doc->narg.text, len);
262                 else
263                         expandhere(redir->nhere.doc, pip[1]);
264                 _exit(0);
265         }
266 out:
267         close(pip[1]);
268         return pip[0];
269 }
270
271
272
273 /*
274  * Undo the effects of the last redirection.
275  */
276
277 void
278 popredir(void)
279 {
280         struct redirtab *rp = redirlist;
281         int i;
282
283         for (i = 0 ; i < 10 ; i++) {
284                 if (rp->renamed[i] != EMPTY) {
285                         if (i == 0)
286                                 fd0_redirected--;
287                         close(i);
288                         if (rp->renamed[i] >= 0) {
289                                 copyfd(rp->renamed[i], i);
290                                 close(rp->renamed[i]);
291                         }
292                 }
293         }
294         INTOFF;
295         redirlist = rp->next;
296         ckfree(rp);
297         INTON;
298 }
299
300 /*
301  * Undo all redirections.  Called on error or interrupt.
302  */
303
304 #ifdef mkinit
305
306 INCLUDE "redir.h"
307
308 RESET {
309         while (redirlist)
310                 popredir();
311 }
312
313 SHELLPROC {
314         clearredir();
315 }
316
317 #endif
318
319 /* Return true if fd 0 has already been redirected at least once.  */
320 int
321 fd0_redirected_p(void)
322 {
323         return fd0_redirected != 0;
324 }
325
326 /*
327  * Discard all saved file descriptors.
328  */
329
330 void
331 clearredir(void)
332 {
333         struct redirtab *rp;
334         int i;
335
336         for (rp = redirlist ; rp ; rp = rp->next) {
337                 for (i = 0 ; i < 10 ; i++) {
338                         if (rp->renamed[i] >= 0) {
339                                 close(rp->renamed[i]);
340                         }
341                         rp->renamed[i] = EMPTY;
342                 }
343         }
344 }
345
346
347
348 /*
349  * Copy a file descriptor to be >= to.  Returns -1
350  * if the source file descriptor is closed, EMPTY if there are no unused
351  * file descriptors left.
352  */
353
354 int
355 copyfd(int from, int to)
356 {
357         int newfd;
358
359         newfd = fcntl(from, F_DUPFD, to);
360         if (newfd < 0) {
361                 if (errno == EMFILE)
362                         return EMPTY;
363                 else
364                         error("%d: %s", from, strerror(errno));
365         }
366         return newfd;
367 }