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