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