xref: /freebsd/bin/sh/input.c (revision dc36d6f9bb1753f3808552f3afd30eda9a7b206a)
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. 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 #endif /* not lint */
35 #include <sys/cdefs.h>
36 #include <stdio.h>	/* defines BUFSIZ */
37 #include <fcntl.h>
38 #include <errno.h>
39 #include <unistd.h>
40 #include <stdlib.h>
41 #include <string.h>
42 
43 /*
44  * This file implements the input routines used by the parser.
45  */
46 
47 #include "shell.h"
48 #include "redir.h"
49 #include "syntax.h"
50 #include "input.h"
51 #include "output.h"
52 #include "options.h"
53 #include "memalloc.h"
54 #include "error.h"
55 #include "alias.h"
56 #include "parser.h"
57 #ifndef NO_HISTORY
58 #include "myhistedit.h"
59 #endif
60 #include "trap.h"
61 
62 #define EOF_NLEFT -99		/* value of parsenleft when EOF pushed back */
63 
64 struct strpush {
65 	struct strpush *prev;	/* preceding string on stack */
66 	const char *prevstring;
67 	int prevnleft;
68 	int prevlleft;
69 	struct alias *ap;	/* if push was associated with an alias */
70 };
71 
72 /*
73  * The parsefile structure pointed to by the global variable parsefile
74  * contains information about the current file being read.
75  */
76 
77 struct parsefile {
78 	struct parsefile *prev;	/* preceding file on stack */
79 	int linno;		/* current line */
80 	int fd;			/* file descriptor (or -1 if string) */
81 	int nleft;		/* number of chars left in this line */
82 	int lleft;		/* number of lines left in this buffer */
83 	const char *nextc;	/* next char in buffer */
84 	char *buf;		/* input buffer */
85 	struct strpush *strpush; /* for pushing strings at this level */
86 	struct strpush basestrpush; /* so pushing one is fast */
87 };
88 
89 
90 int plinno = 1;			/* input line number */
91 int parsenleft;			/* copy of parsefile->nleft */
92 static int parselleft;		/* copy of parsefile->lleft */
93 const char *parsenextc;		/* copy of parsefile->nextc */
94 static char basebuf[BUFSIZ + 1];/* buffer for top level input file */
95 static struct parsefile basepf = {	/* top level input file */
96 	.nextc = basebuf,
97 	.buf = basebuf
98 };
99 static struct parsefile *parsefile = &basepf;	/* current input file */
100 int whichprompt;		/* 1 == PS1, 2 == PS2 */
101 
102 static void pushfile(void);
103 static int preadfd(void);
104 static void popstring(void);
105 
106 void
107 resetinput(void)
108 {
109 	popallfiles();
110 	parselleft = parsenleft = 0;	/* clear input buffer */
111 }
112 
113 
114 
115 /*
116  * Read a character from the script, returning PEOF on end of file.
117  * Nul characters in the input are silently discarded.
118  */
119 
120 int
121 pgetc(void)
122 {
123 	return pgetc_macro();
124 }
125 
126 
127 static int
128 preadfd(void)
129 {
130 	int nr;
131 	parsenextc = parsefile->buf;
132 
133 retry:
134 #ifndef NO_HISTORY
135 	if (parsefile->fd == 0 && el) {
136 		static const char *rl_cp;
137 		static int el_len;
138 
139 		if (rl_cp == NULL) {
140 			el_resize(el);
141 			rl_cp = el_gets(el, &el_len);
142 		}
143 		if (rl_cp == NULL)
144 			nr = el_len == 0 ? 0 : -1;
145 		else {
146 			nr = el_len;
147 			if (nr > BUFSIZ)
148 				nr = BUFSIZ;
149 			memcpy(parsefile->buf, rl_cp, nr);
150 			if (nr != el_len) {
151 				el_len -= nr;
152 				rl_cp += nr;
153 			} else
154 				rl_cp = NULL;
155 		}
156 	} else
157 #endif
158 		nr = read(parsefile->fd, parsefile->buf, BUFSIZ);
159 
160 	if (nr <= 0) {
161                 if (nr < 0) {
162                         if (errno == EINTR)
163                                 goto retry;
164                         if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
165                                 int flags = fcntl(0, F_GETFL, 0);
166                                 if (flags >= 0 && flags & O_NONBLOCK) {
167                                         flags &=~ O_NONBLOCK;
168                                         if (fcntl(0, F_SETFL, flags) >= 0) {
169 						out2fmt_flush("sh: turning off NDELAY mode\n");
170                                                 goto retry;
171                                         }
172                                 }
173                         }
174                 }
175                 nr = -1;
176 	}
177 	return nr;
178 }
179 
180 /*
181  * Refill the input buffer and return the next input character:
182  *
183  * 1) If a string was pushed back on the input, pop it;
184  * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
185  *    from a string so we can't refill the buffer, return EOF.
186  * 3) If there is more in this buffer, use it else call read to fill it.
187  * 4) Process input up to the next newline, deleting nul characters.
188  */
189 
190 int
191 preadbuffer(void)
192 {
193 	char *p, *q, *r, *end;
194 	char savec;
195 
196 	while (parsefile->strpush) {
197 		/*
198 		 * Add a space to the end of an alias to ensure that the
199 		 * alias remains in use while parsing its last word.
200 		 * This avoids alias recursions.
201 		 */
202 		if (parsenleft == -1 && parsefile->strpush->ap != NULL)
203 			return ' ';
204 		popstring();
205 		if (--parsenleft >= 0)
206 			return (*parsenextc++);
207 	}
208 	if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
209 		return PEOF;
210 
211 again:
212 	if (parselleft <= 0) {
213 		if ((parselleft = preadfd()) == -1) {
214 			parselleft = parsenleft = EOF_NLEFT;
215 			return PEOF;
216 		}
217 	}
218 
219 	p = parsefile->buf + (parsenextc - parsefile->buf);
220 	end = p + parselleft;
221 	*end = '\0';
222 	q = strchrnul(p, '\n');
223 	if (q != end && *q == '\0') {
224 		/* delete nul characters */
225 		for (r = q; q != end; q++) {
226 			if (*q != '\0')
227 				*r++ = *q;
228 		}
229 		parselleft -= end - r;
230 		if (parselleft == 0)
231 			goto again;
232 		end = p + parselleft;
233 		*end = '\0';
234 		q = strchrnul(p, '\n');
235 	}
236 	if (q == end) {
237 		parsenleft = parselleft;
238 		parselleft = 0;
239 	} else /* *q == '\n' */ {
240 		q++;
241 		parsenleft = q - parsenextc;
242 		parselleft -= parsenleft;
243 	}
244 	parsenleft--;
245 
246 	savec = *q;
247 	*q = '\0';
248 
249 #ifndef NO_HISTORY
250 	if (parsefile->fd == 0 && hist &&
251 	    parsenextc[strspn(parsenextc, " \t\n")] != '\0') {
252 		HistEvent he;
253 		INTOFF;
254 		history(hist, &he, whichprompt == 1 ? H_ENTER : H_ADD,
255 		    parsenextc);
256 		INTON;
257 	}
258 #endif
259 
260 	if (vflag) {
261 		out2str(parsenextc);
262 		flushout(out2);
263 	}
264 
265 	*q = savec;
266 
267 	return *parsenextc++;
268 }
269 
270 /*
271  * Returns if we are certain we are at EOF. Does not cause any more input
272  * to be read from the outside world.
273  */
274 
275 int
276 preadateof(void)
277 {
278 	if (parsenleft > 0)
279 		return 0;
280 	if (parsefile->strpush)
281 		return 0;
282 	if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
283 		return 1;
284 	return 0;
285 }
286 
287 /*
288  * Undo the last call to pgetc.  Only one character may be pushed back.
289  * PEOF may be pushed back.
290  */
291 
292 void
293 pungetc(void)
294 {
295 	parsenleft++;
296 	parsenextc--;
297 }
298 
299 /*
300  * Push a string back onto the input at this current parsefile level.
301  * We handle aliases this way.
302  */
303 void
304 pushstring(const char *s, int len, struct alias *ap)
305 {
306 	struct strpush *sp;
307 
308 	INTOFF;
309 /*out2fmt_flush("*** calling pushstring: %s, %d\n", s, len);*/
310 	if (parsefile->strpush) {
311 		sp = ckmalloc(sizeof (struct strpush));
312 		sp->prev = parsefile->strpush;
313 		parsefile->strpush = sp;
314 	} else
315 		sp = parsefile->strpush = &(parsefile->basestrpush);
316 	sp->prevstring = parsenextc;
317 	sp->prevnleft = parsenleft;
318 	sp->prevlleft = parselleft;
319 	sp->ap = ap;
320 	if (ap)
321 		ap->flag |= ALIASINUSE;
322 	parsenextc = s;
323 	parsenleft = len;
324 	INTON;
325 }
326 
327 static void
328 popstring(void)
329 {
330 	struct strpush *sp = parsefile->strpush;
331 
332 	INTOFF;
333 	if (sp->ap) {
334 		if (parsenextc != sp->ap->val &&
335 		    (parsenextc[-1] == ' ' || parsenextc[-1] == '\t'))
336 			forcealias();
337 		sp->ap->flag &= ~ALIASINUSE;
338 	}
339 	parsenextc = sp->prevstring;
340 	parsenleft = sp->prevnleft;
341 	parselleft = sp->prevlleft;
342 /*out2fmt_flush("*** calling popstring: restoring to '%s'\n", parsenextc);*/
343 	parsefile->strpush = sp->prev;
344 	if (sp != &(parsefile->basestrpush))
345 		ckfree(sp);
346 	INTON;
347 }
348 
349 /*
350  * Set the input to take input from a file.  If push is set, push the
351  * old input onto the stack first.
352  * About verify:
353  *   -1: Obey verifyflag
354  *    0: Do not verify
355  *    1: Do verify
356  */
357 
358 void
359 setinputfile(const char *fname, int push, int verify)
360 {
361 	int e;
362 	int fd;
363 	int fd2;
364 	int oflags = O_RDONLY | O_CLOEXEC;
365 
366 	if (verify == 1 || (verify == -1 && verifyflag))
367 		oflags |= O_VERIFY;
368 
369 	INTOFF;
370 	if ((fd = open(fname, oflags)) < 0) {
371 		e = errno;
372 		errorwithstatus(e == ENOENT || e == ENOTDIR ? 127 : 126,
373 		    "cannot open %s: %s", fname, strerror(e));
374 	}
375 	if (fd < 10) {
376 		fd2 = fcntl(fd, F_DUPFD_CLOEXEC, 10);
377 		close(fd);
378 		if (fd2 < 0)
379 			error("Out of file descriptors");
380 		fd = fd2;
381 	}
382 	setinputfd(fd, push);
383 	INTON;
384 }
385 
386 
387 /*
388  * Like setinputfile, but takes an open file descriptor (which should have
389  * its FD_CLOEXEC flag already set).  Call this with interrupts off.
390  */
391 
392 void
393 setinputfd(int fd, int push)
394 {
395 	if (push) {
396 		pushfile();
397 		parsefile->buf = ckmalloc(BUFSIZ + 1);
398 	}
399 	if (parsefile->fd > 0)
400 		close(parsefile->fd);
401 	parsefile->fd = fd;
402 	if (parsefile->buf == NULL)
403 		parsefile->buf = ckmalloc(BUFSIZ + 1);
404 	parselleft = parsenleft = 0;
405 	plinno = 1;
406 }
407 
408 
409 /*
410  * Like setinputfile, but takes input from a string.
411  */
412 
413 void
414 setinputstring(const char *string, int push)
415 {
416 	INTOFF;
417 	if (push)
418 		pushfile();
419 	parsenextc = string;
420 	parselleft = parsenleft = strlen(string);
421 	parsefile->buf = NULL;
422 	plinno = 1;
423 	INTON;
424 }
425 
426 
427 
428 /*
429  * To handle the "." command, a stack of input files is used.  Pushfile
430  * adds a new entry to the stack and popfile restores the previous level.
431  */
432 
433 static void
434 pushfile(void)
435 {
436 	struct parsefile *pf;
437 
438 	parsefile->nleft = parsenleft;
439 	parsefile->lleft = parselleft;
440 	parsefile->nextc = parsenextc;
441 	parsefile->linno = plinno;
442 	pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
443 	pf->prev = parsefile;
444 	pf->fd = -1;
445 	pf->strpush = NULL;
446 	pf->basestrpush.prev = NULL;
447 	parsefile = pf;
448 }
449 
450 
451 void
452 popfile(void)
453 {
454 	struct parsefile *pf = parsefile;
455 
456 	INTOFF;
457 	if (pf->fd >= 0)
458 		close(pf->fd);
459 	if (pf->buf)
460 		ckfree(pf->buf);
461 	while (pf->strpush)
462 		popstring();
463 	parsefile = pf->prev;
464 	ckfree(pf);
465 	parsenleft = parsefile->nleft;
466 	parselleft = parsefile->lleft;
467 	parsenextc = parsefile->nextc;
468 	plinno = parsefile->linno;
469 	INTON;
470 }
471 
472 
473 /*
474  * Return current file (to go back to it later using popfilesupto()).
475  */
476 
477 struct parsefile *
478 getcurrentfile(void)
479 {
480 	return parsefile;
481 }
482 
483 
484 /*
485  * Pop files until the given file is on top again. Useful for regular
486  * builtins that read shell commands from files or strings.
487  * If the given file is not an active file, an error is raised.
488  */
489 
490 void
491 popfilesupto(struct parsefile *file)
492 {
493 	while (parsefile != file && parsefile != &basepf)
494 		popfile();
495 	if (parsefile != file)
496 		error("popfilesupto() misused");
497 }
498 
499 /*
500  * Return to top level.
501  */
502 
503 void
504 popallfiles(void)
505 {
506 	while (parsefile != &basepf)
507 		popfile();
508 }
509 
510 
511 
512 /*
513  * Close the file(s) that the shell is reading commands from.  Called
514  * after a fork is done.
515  */
516 
517 void
518 closescript(void)
519 {
520 	popallfiles();
521 	if (parsefile->fd > 0) {
522 		close(parsefile->fd);
523 		parsefile->fd = 0;
524 	}
525 }
526