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