xref: /freebsd/bin/sh/input.c (revision 68e7a217f8019b955f87547f218e95ab237597af)
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. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 #if 0
39 static char sccsid[] = "@(#)input.c	8.3 (Berkeley) 6/9/95";
40 #endif
41 static const char rcsid[] =
42   "$FreeBSD$";
43 #endif /* not lint */
44 
45 #include <stdio.h>	/* defines BUFSIZ */
46 #include <fcntl.h>
47 #include <errno.h>
48 #include <unistd.h>
49 #include <stdlib.h>
50 #include <string.h>
51 
52 /*
53  * This file implements the input routines used by the parser.
54  */
55 
56 #include "shell.h"
57 #include "redir.h"
58 #include "syntax.h"
59 #include "input.h"
60 #include "output.h"
61 #include "options.h"
62 #include "memalloc.h"
63 #include "error.h"
64 #include "alias.h"
65 #include "parser.h"
66 #include "myhistedit.h"
67 
68 #define EOF_NLEFT -99		/* value of parsenleft when EOF pushed back */
69 
70 MKINIT
71 struct strpush {
72 	struct strpush *prev;	/* preceding string on stack */
73 	char *prevstring;
74 	int prevnleft;
75 	int prevlleft;
76 	struct alias *ap;	/* if push was associated with an alias */
77 };
78 
79 /*
80  * The parsefile structure pointed to by the global variable parsefile
81  * contains information about the current file being read.
82  */
83 
84 MKINIT
85 struct parsefile {
86 	struct parsefile *prev;	/* preceding file on stack */
87 	int linno;		/* current line */
88 	int fd;			/* file descriptor (or -1 if string) */
89 	int nleft;		/* number of chars left in this line */
90 	int lleft;		/* number of lines left in this buffer */
91 	char *nextc;		/* next char in buffer */
92 	char *buf;		/* input buffer */
93 	struct strpush *strpush; /* for pushing strings at this level */
94 	struct strpush basestrpush; /* so pushing one is fast */
95 };
96 
97 
98 int plinno = 1;			/* input line number */
99 MKINIT int parsenleft;		/* copy of parsefile->nleft */
100 MKINIT int parselleft;		/* copy of parsefile->lleft */
101 char *parsenextc;		/* copy of parsefile->nextc */
102 MKINIT struct parsefile basepf;	/* top level input file */
103 char basebuf[BUFSIZ];		/* buffer for top level input file */
104 struct parsefile *parsefile = &basepf;	/* current input file */
105 int init_editline = 0;		/* editline library initialized? */
106 int whichprompt;		/* 1 == PS1, 2 == PS2 */
107 
108 EditLine *el;			/* cookie for editline package */
109 
110 STATIC void pushfile(void);
111 static int preadfd(void);
112 
113 #ifdef mkinit
114 INCLUDE "input.h"
115 INCLUDE "error.h"
116 
117 INIT {
118 	extern char basebuf[];
119 
120 	basepf.nextc = basepf.buf = basebuf;
121 }
122 
123 RESET {
124 	if (exception != EXSHELLPROC)
125 		parselleft = parsenleft = 0;	/* clear input buffer */
126 	popallfiles();
127 }
128 
129 SHELLPROC {
130 	popallfiles();
131 }
132 #endif
133 
134 
135 /*
136  * Read a line from the script.
137  */
138 
139 char *
140 pfgets(char *line, int len)
141 {
142 	char *p = line;
143 	int nleft = len;
144 	int c;
145 
146 	while (--nleft > 0) {
147 		c = pgetc_macro();
148 		if (c == PEOF) {
149 			if (p == line)
150 				return NULL;
151 			break;
152 		}
153 		*p++ = c;
154 		if (c == '\n')
155 			break;
156 	}
157 	*p = '\0';
158 	return line;
159 }
160 
161 
162 
163 /*
164  * Read a character from the script, returning PEOF on end of file.
165  * Nul characters in the input are silently discarded.
166  */
167 
168 int
169 pgetc(void)
170 {
171 	return pgetc_macro();
172 }
173 
174 
175 static int
176 preadfd(void)
177 {
178 	int nr;
179 	parsenextc = parsefile->buf;
180 
181 retry:
182 #ifndef NO_HISTORY
183 	if (parsefile->fd == 0 && el) {
184 		const char *rl_cp;
185 
186 		rl_cp = el_gets(el, &nr);
187 		if (rl_cp == NULL)
188 			nr = 0;
189 		else {
190 			/* XXX - BUFSIZE should redesign so not necessary */
191 			(void) strcpy(parsenextc, rl_cp);
192 		}
193 	} else
194 #endif
195 		nr = read(parsefile->fd, parsenextc, BUFSIZ - 1);
196 
197 	if (nr <= 0) {
198                 if (nr < 0) {
199                         if (errno == EINTR)
200                                 goto retry;
201                         if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
202                                 int flags = fcntl(0, F_GETFL, 0);
203                                 if (flags >= 0 && flags & O_NONBLOCK) {
204                                         flags &=~ O_NONBLOCK;
205                                         if (fcntl(0, F_SETFL, flags) >= 0) {
206 						out2str("sh: turning off NDELAY mode\n");
207                                                 goto retry;
208                                         }
209                                 }
210                         }
211                 }
212                 nr = -1;
213 	}
214 	return nr;
215 }
216 
217 /*
218  * Refill the input buffer and return the next input character:
219  *
220  * 1) If a string was pushed back on the input, pop it;
221  * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
222  *    from a string so we can't refill the buffer, return EOF.
223  * 3) If there is more in this buffer, use it else call read to fill it.
224  * 4) Process input up to the next newline, deleting nul characters.
225  */
226 
227 int
228 preadbuffer(void)
229 {
230 	char *p, *q;
231 	int more;
232 	int something;
233 	char savec;
234 
235 	if (parsefile->strpush) {
236 		popstring();
237 		if (--parsenleft >= 0)
238 			return (*parsenextc++);
239 	}
240 	if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
241 		return PEOF;
242 	flushout(&output);
243 	flushout(&errout);
244 
245 again:
246 	if (parselleft <= 0) {
247 		if ((parselleft = preadfd()) == -1) {
248 			parselleft = parsenleft = EOF_NLEFT;
249 			return PEOF;
250 		}
251 	}
252 
253 	q = p = parsenextc;
254 
255 	/* delete nul characters */
256 	something = 0;
257 	for (more = 1; more;) {
258 		switch (*p) {
259 		case '\0':
260 			p++;	/* Skip nul */
261 			goto check;
262 
263 		case '\t':
264 		case ' ':
265 			break;
266 
267 		case '\n':
268 			parsenleft = q - parsenextc;
269 			more = 0; /* Stop processing here */
270 			break;
271 
272 		default:
273 			something = 1;
274 			break;
275 		}
276 
277 		*q++ = *p++;
278 check:
279 		if (--parselleft <= 0) {
280 			parsenleft = q - parsenextc - 1;
281 			if (parsenleft < 0)
282 				goto again;
283 			*q = '\0';
284 			more = 0;
285 		}
286 	}
287 
288 	savec = *q;
289 	*q = '\0';
290 
291 #ifndef NO_HISTORY
292 	if (parsefile->fd == 0 && hist && something) {
293 		HistEvent he;
294 		INTOFF;
295 		history(hist, &he, whichprompt == 1 ? H_ENTER : H_ADD,
296 		    parsenextc);
297 		INTON;
298 	}
299 #endif
300 
301 	if (vflag) {
302 		out2str(parsenextc);
303 		flushout(out2);
304 	}
305 
306 	*q = savec;
307 
308 	return *parsenextc++;
309 }
310 
311 /*
312  * Undo the last call to pgetc.  Only one character may be pushed back.
313  * PEOF may be pushed back.
314  */
315 
316 void
317 pungetc(void)
318 {
319 	parsenleft++;
320 	parsenextc--;
321 }
322 
323 /*
324  * Push a string back onto the input at this current parsefile level.
325  * We handle aliases this way.
326  */
327 void
328 pushstring(char *s, int len, void *ap)
329 {
330 	struct strpush *sp;
331 
332 	INTOFF;
333 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
334 	if (parsefile->strpush) {
335 		sp = ckmalloc(sizeof (struct strpush));
336 		sp->prev = parsefile->strpush;
337 		parsefile->strpush = sp;
338 	} else
339 		sp = parsefile->strpush = &(parsefile->basestrpush);
340 	sp->prevstring = parsenextc;
341 	sp->prevnleft = parsenleft;
342 	sp->prevlleft = parselleft;
343 	sp->ap = (struct alias *)ap;
344 	if (ap)
345 		((struct alias *)ap)->flag |= ALIASINUSE;
346 	parsenextc = s;
347 	parsenleft = len;
348 	INTON;
349 }
350 
351 void
352 popstring(void)
353 {
354 	struct strpush *sp = parsefile->strpush;
355 
356 	INTOFF;
357 	parsenextc = sp->prevstring;
358 	parsenleft = sp->prevnleft;
359 	parselleft = sp->prevlleft;
360 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
361 	if (sp->ap)
362 		sp->ap->flag &= ~ALIASINUSE;
363 	parsefile->strpush = sp->prev;
364 	if (sp != &(parsefile->basestrpush))
365 		ckfree(sp);
366 	INTON;
367 }
368 
369 /*
370  * Set the input to take input from a file.  If push is set, push the
371  * old input onto the stack first.
372  */
373 
374 void
375 setinputfile(char *fname, int push)
376 {
377 	int fd;
378 	int fd2;
379 
380 	INTOFF;
381 	if ((fd = open(fname, O_RDONLY)) < 0)
382 		error("Can't open %s: %s", fname, strerror(errno));
383 	if (fd < 10) {
384 		fd2 = copyfd(fd, 10);
385 		close(fd);
386 		if (fd2 < 0)
387 			error("Out of file descriptors");
388 		fd = fd2;
389 	}
390 	setinputfd(fd, push);
391 	INTON;
392 }
393 
394 
395 /*
396  * Like setinputfile, but takes an open file descriptor.  Call this with
397  * interrupts off.
398  */
399 
400 void
401 setinputfd(int fd, int push)
402 {
403 	(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
404 	if (push) {
405 		pushfile();
406 		parsefile->buf = ckmalloc(BUFSIZ);
407 	}
408 	if (parsefile->fd > 0)
409 		close(parsefile->fd);
410 	parsefile->fd = fd;
411 	if (parsefile->buf == NULL)
412 		parsefile->buf = ckmalloc(BUFSIZ);
413 	parselleft = parsenleft = 0;
414 	plinno = 1;
415 }
416 
417 
418 /*
419  * Like setinputfile, but takes input from a string.
420  */
421 
422 void
423 setinputstring(char *string, int push)
424 {
425 	INTOFF;
426 	if (push)
427 		pushfile();
428 	parsenextc = string;
429 	parselleft = parsenleft = strlen(string);
430 	parsefile->buf = NULL;
431 	plinno = 1;
432 	INTON;
433 }
434 
435 
436 
437 /*
438  * To handle the "." command, a stack of input files is used.  Pushfile
439  * adds a new entry to the stack and popfile restores the previous level.
440  */
441 
442 STATIC void
443 pushfile(void)
444 {
445 	struct parsefile *pf;
446 
447 	parsefile->nleft = parsenleft;
448 	parsefile->lleft = parselleft;
449 	parsefile->nextc = parsenextc;
450 	parsefile->linno = plinno;
451 	pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
452 	pf->prev = parsefile;
453 	pf->fd = -1;
454 	pf->strpush = NULL;
455 	pf->basestrpush.prev = NULL;
456 	parsefile = pf;
457 }
458 
459 
460 void
461 popfile(void)
462 {
463 	struct parsefile *pf = parsefile;
464 
465 	INTOFF;
466 	if (pf->fd >= 0)
467 		close(pf->fd);
468 	if (pf->buf)
469 		ckfree(pf->buf);
470 	while (pf->strpush)
471 		popstring();
472 	parsefile = pf->prev;
473 	ckfree(pf);
474 	parsenleft = parsefile->nleft;
475 	parselleft = parsefile->lleft;
476 	parsenextc = parsefile->nextc;
477 	plinno = parsefile->linno;
478 	INTON;
479 }
480 
481 
482 /*
483  * Return to top level.
484  */
485 
486 void
487 popallfiles(void)
488 {
489 	while (parsefile != &basepf)
490 		popfile();
491 }
492 
493 
494 
495 /*
496  * Close the file(s) that the shell is reading commands from.  Called
497  * after a fork is done.
498  */
499 
500 void
501 closescript(void)
502 {
503 	popallfiles();
504 	if (parsefile->fd > 0) {
505 		close(parsefile->fd);
506 		parsefile->fd = 0;
507 	}
508 }
509