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