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