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