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