xref: /freebsd/bin/sh/redir.c (revision 97bd480fe38abb5950359b9d864a62037b4ab5f7)
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 struct redirtab {
70 	struct redirtab *next;
71 	int renamed[10];
72 	int fd0_redirected;
73 };
74 
75 
76 static 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->fd0_redirected = fd0_redirected;
114 		sv->next = redirlist;
115 		redirlist = sv;
116 	}
117 	for (n = redir ; n ; n = n->nfile.next) {
118 		fd = n->nfile.fd;
119 		if (fd == 0)
120 			fd0_redirected = 1;
121 		if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
122 		    n->ndup.dupfd == fd)
123 			continue; /* redirect from/to same file descriptor */
124 
125 		if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
126 			INTOFF;
127 			if ((i = fcntl(fd, F_DUPFD_CLOEXEC, 10)) == -1) {
128 				switch (errno) {
129 				case EBADF:
130 					i = CLOSED;
131 					break;
132 				default:
133 					INTON;
134 					error("%d: %s", fd, strerror(errno));
135 					break;
136 				}
137 			}
138 			sv->renamed[fd] = i;
139 			INTON;
140 		}
141 		openredirect(n, memory);
142 	}
143 	if (memory[1])
144 		out1 = &memout;
145 	if (memory[2])
146 		out2 = &memout;
147 }
148 
149 
150 static void
151 openredirect(union node *redir, char memory[10])
152 {
153 	struct stat sb;
154 	int fd = redir->nfile.fd;
155 	const char *fname;
156 	int f;
157 	int e;
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 			if (dup2(f, fd) == -1) {
177 				e = errno;
178 				close(f);
179 				error("%d: %s", fd, strerror(e));
180 			}
181 			close(f);
182 		}
183 		break;
184 	case NFROMTO:
185 		fname = redir->nfile.expfname;
186 		if ((f = open(fname, O_RDWR|O_CREAT, 0666)) < 0)
187 			error("cannot create %s: %s", fname, strerror(errno));
188 		goto movefd;
189 	case NTO:
190 		if (Cflag) {
191 			fname = redir->nfile.expfname;
192 			if (stat(fname, &sb) == -1) {
193 				if ((f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666)) < 0)
194 					error("cannot create %s: %s", fname, strerror(errno));
195 			} else if (!S_ISREG(sb.st_mode)) {
196 				if ((f = open(fname, O_WRONLY, 0666)) < 0)
197 					error("cannot create %s: %s", fname, strerror(errno));
198 				if (fstat(f, &sb) != -1 && S_ISREG(sb.st_mode)) {
199 					close(f);
200 					error("cannot create %s: %s", fname,
201 					    strerror(EEXIST));
202 				}
203 			} else
204 				error("cannot create %s: %s", fname,
205 				    strerror(EEXIST));
206 			goto movefd;
207 		}
208 		/* FALLTHROUGH */
209 	case NCLOBBER:
210 		fname = redir->nfile.expfname;
211 		if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
212 			error("cannot create %s: %s", fname, strerror(errno));
213 		goto movefd;
214 	case NAPPEND:
215 		fname = redir->nfile.expfname;
216 		if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
217 			error("cannot create %s: %s", fname, strerror(errno));
218 		goto movefd;
219 	case NTOFD:
220 	case NFROMFD:
221 		if (redir->ndup.dupfd >= 0) {	/* if not ">&-" */
222 			if (memory[redir->ndup.dupfd])
223 				memory[fd] = 1;
224 			else {
225 				if (dup2(redir->ndup.dupfd, fd) < 0)
226 					error("%d: %s", redir->ndup.dupfd,
227 							strerror(errno));
228 			}
229 		} else {
230 			close(fd);
231 		}
232 		break;
233 	case NHERE:
234 	case NXHERE:
235 		f = openhere(redir);
236 		goto movefd;
237 	default:
238 		abort();
239 	}
240 	INTON;
241 }
242 
243 
244 /*
245  * Handle here documents.  Normally we fork off a process to write the
246  * data to a pipe.  If the document is short, we can stuff the data in
247  * the pipe without forking.
248  */
249 
250 static int
251 openhere(union node *redir)
252 {
253 	const char *p;
254 	int pip[2];
255 	size_t len = 0;
256 	int flags;
257 	ssize_t written = 0;
258 
259 	if (pipe(pip) < 0)
260 		error("Pipe call failed: %s", strerror(errno));
261 
262 	if (redir->type == NXHERE)
263 		p = redir->nhere.expdoc;
264 	else
265 		p = redir->nhere.doc->narg.text;
266 	len = strlen(p);
267 	if (len == 0)
268 		goto out;
269 	flags = fcntl(pip[1], F_GETFL, 0);
270 	if (flags != -1 && fcntl(pip[1], F_SETFL, flags | O_NONBLOCK) != -1) {
271 		written = write(pip[1], p, len);
272 		if (written < 0)
273 			written = 0;
274 		if ((size_t)written == len)
275 			goto out;
276 		fcntl(pip[1], F_SETFL, flags);
277 	}
278 
279 	if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
280 		close(pip[0]);
281 		signal(SIGINT, SIG_IGN);
282 		signal(SIGQUIT, SIG_IGN);
283 		signal(SIGHUP, SIG_IGN);
284 		signal(SIGTSTP, SIG_IGN);
285 		signal(SIGPIPE, SIG_DFL);
286 		xwrite(pip[1], p + written, len - written);
287 		_exit(0);
288 	}
289 out:
290 	close(pip[1]);
291 	return pip[0];
292 }
293 
294 
295 
296 /*
297  * Undo the effects of the last redirection.
298  */
299 
300 void
301 popredir(void)
302 {
303 	struct redirtab *rp = redirlist;
304 	int i;
305 
306 	for (i = 0 ; i < 10 ; i++) {
307 		if (rp->renamed[i] != EMPTY) {
308 			if (rp->renamed[i] >= 0) {
309 				dup2(rp->renamed[i], i);
310 				close(rp->renamed[i]);
311 			} else {
312 				close(i);
313 			}
314 		}
315 	}
316 	INTOFF;
317 	fd0_redirected = rp->fd0_redirected;
318 	redirlist = rp->next;
319 	ckfree(rp);
320 	INTON;
321 }
322 
323 /* Return true if fd 0 has already been redirected at least once.  */
324 int
325 fd0_redirected_p(void)
326 {
327         return fd0_redirected != 0;
328 }
329 
330 /*
331  * Discard all saved file descriptors.
332  */
333 
334 void
335 clearredir(void)
336 {
337 	struct redirtab *rp;
338 	int i;
339 
340 	for (rp = redirlist ; rp ; rp = rp->next) {
341 		for (i = 0 ; i < 10 ; i++) {
342 			if (rp->renamed[i] >= 0) {
343 				close(rp->renamed[i]);
344 			}
345 			rp->renamed[i] = EMPTY;
346 		}
347 	}
348 }
349