1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1997-2005
5  *	Herbert Xu <herbert@gondor.apana.org.au>.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Kenneth Almquist.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <stdio.h>	/* defines BUFSIZ */
36 #include <fcntl.h>
37 #include <unistd.h>
38 #include <stdlib.h>
39 #include <string.h>
40 
41 /*
42  * This file implements the input routines used by the parser.
43  */
44 
45 #include "eval.h"
46 #include "shell.h"
47 #include "redir.h"
48 #include "syntax.h"
49 #include "input.h"
50 #include "output.h"
51 #include "options.h"
52 #include "memalloc.h"
53 #include "error.h"
54 #include "alias.h"
55 #include "parser.h"
56 #include "main.h"
57 #ifndef SMALL
58 #include "myhistedit.h"
59 #endif
60 
61 #define EOF_NLEFT -99		/* value of parsenleft when EOF pushed back */
62 #define IBUFSIZ (BUFSIZ + 1)
63 
64 
65 MKINIT struct parsefile basepf;	/* top level input file */
66 MKINIT char basebuf[IBUFSIZ];	/* buffer for top level input file */
67 struct parsefile *parsefile = &basepf;	/* current input file */
68 int whichprompt;		/* 1 == PS1, 2 == PS2 */
69 
70 STATIC void pushfile(void);
71 static int preadfd(void);
72 static void setinputfd(int fd, int push);
73 static int preadbuffer(void);
74 
75 #ifdef mkinit
76 INCLUDE <stdio.h>
77 INCLUDE <unistd.h>
78 INCLUDE "input.h"
79 INCLUDE "error.h"
80 
81 INIT {
82 	basepf.nextc = basepf.buf = basebuf;
83 	basepf.linno = 1;
84 }
85 
86 RESET {
87 	/* clear input buffer */
88 	basepf.lleft = basepf.nleft = 0;
89 	popallfiles();
90 }
91 
92 FORKRESET {
93 	popallfiles();
94 	if (parsefile->fd > 0) {
95 		close(parsefile->fd);
96 		parsefile->fd = 0;
97 	}
98 }
99 #endif
100 
101 
102 /*
103  * Read a character from the script, returning PEOF on end of file.
104  * Nul characters in the input are silently discarded.
105  */
106 
107 int
pgetc(void)108 pgetc(void)
109 {
110 	int c;
111 
112 	if (parsefile->unget)
113 		return parsefile->lastc[--parsefile->unget];
114 
115 	if (--parsefile->nleft >= 0)
116 		c = (signed char)*parsefile->nextc++;
117 	else
118 		c = preadbuffer();
119 
120 	parsefile->lastc[1] = parsefile->lastc[0];
121 	parsefile->lastc[0] = c;
122 
123 	return c;
124 }
125 
126 
127 /*
128  * Same as pgetc(), but ignores PEOA.
129  */
130 
131 int
pgetc2()132 pgetc2()
133 {
134 	int c;
135 	do {
136 		c = pgetc();
137 	} while (c == PEOA);
138 	return c;
139 }
140 
141 
142 static int
preadfd(void)143 preadfd(void)
144 {
145 	int nr;
146 	char *buf =  parsefile->buf;
147 	parsefile->nextc = buf;
148 
149 retry:
150 #ifndef SMALL
151 	if (parsefile->fd == 0 && el) {
152 		static const char *rl_cp;
153 		static int el_len;
154 
155 		if (rl_cp == NULL) {
156 			struct stackmark smark;
157 			pushstackmark(&smark, stackblocksize());
158 			rl_cp = el_gets(el, &el_len);
159 			popstackmark(&smark);
160 		}
161 		if (rl_cp == NULL)
162 			nr = 0;
163 		else {
164 			nr = el_len;
165 			if (nr > IBUFSIZ - 1)
166 				nr = IBUFSIZ - 1;
167 			memcpy(buf, rl_cp, nr);
168 			if (nr != el_len) {
169 				el_len -= nr;
170 				rl_cp += nr;
171 			} else
172 				rl_cp = 0;
173 		}
174 
175 	} else
176 #endif
177 		nr = read(parsefile->fd, buf, IBUFSIZ - 1);
178 
179 
180 	if (nr < 0) {
181 		if (errno == EINTR)
182 			goto retry;
183 		if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
184 			int flags = fcntl(0, F_GETFL, 0);
185 			if (flags >= 0 && flags & O_NONBLOCK) {
186 				flags &=~ O_NONBLOCK;
187 				if (fcntl(0, F_SETFL, flags) >= 0) {
188 					out2str("sh: turning off NDELAY mode\n");
189 					goto retry;
190 				}
191 			}
192 		}
193 	}
194 	return nr;
195 }
196 
197 /*
198  * Refill the input buffer and return the next input character:
199  *
200  * 1) If a string was pushed back on the input, pop it;
201  * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
202  *    from a string so we can't refill the buffer, return EOF.
203  * 3) If the is more stuff in this buffer, use it else call read to fill it.
204  * 4) Process input up to the next newline, deleting nul characters.
205  */
206 
preadbuffer(void)207 static int preadbuffer(void)
208 {
209 	char *q;
210 	int more;
211 #ifndef SMALL
212 	int something;
213 #endif
214 	char savec;
215 
216 	if (unlikely(parsefile->strpush)) {
217 		if (
218 			parsefile->nleft == -1 &&
219 			parsefile->strpush->ap &&
220 			parsefile->nextc[-1] != ' ' &&
221 			parsefile->nextc[-1] != '\t'
222 		) {
223 			return PEOA;
224 		}
225 		popstring();
226 		return pgetc();
227 	}
228 	if (unlikely(parsefile->nleft == EOF_NLEFT ||
229 		     parsefile->buf == NULL))
230 		return PEOF;
231 	flushall();
232 
233 	more = parsefile->lleft;
234 	if (more <= 0) {
235 again:
236 		if ((more = preadfd()) <= 0) {
237 			parsefile->lleft = parsefile->nleft = EOF_NLEFT;
238 			return PEOF;
239 		}
240 	}
241 
242 	q = parsefile->nextc;
243 
244 	/* delete nul characters */
245 #ifndef SMALL
246 	something = 0;
247 #endif
248 	for (;;) {
249 		int c;
250 
251 		more--;
252 		c = *q;
253 
254 		if (!c)
255 			memmove(q, q + 1, more);
256 		else {
257 			q++;
258 
259 			if (c == '\n') {
260 				parsefile->nleft = q - parsefile->nextc - 1;
261 				break;
262 			}
263 
264 #ifndef SMALL
265 			switch (c) {
266 			default:
267 				something = 1;
268 				/* fall through */
269 			case '\t':
270 			case ' ':
271 				break;
272 			}
273 #endif
274 		}
275 
276 		if (more <= 0) {
277 			parsefile->nleft = q - parsefile->nextc - 1;
278 			if (parsefile->nleft < 0)
279 				goto again;
280 			break;
281 		}
282 	}
283 	parsefile->lleft = more;
284 
285 	savec = *q;
286 	*q = '\0';
287 
288 #ifndef SMALL
289 	if (parsefile->fd == 0 && hist && something) {
290 		HistEvent he;
291 		INTOFF;
292 		history(hist, &he, whichprompt == 1? H_ENTER : H_APPEND,
293 			parsefile->nextc);
294 		INTON;
295 	}
296 #endif
297 
298 	if (vflag) {
299 		out2str(parsefile->nextc);
300 #ifdef FLUSHERR
301 		flushout(out2);
302 #endif
303 	}
304 
305 	*q = savec;
306 
307 	return (signed char)*parsefile->nextc++;
308 }
309 
310 /*
311  * Undo a call to pgetc.  Only two characters may be pushed back.
312  * PEOF may be pushed back.
313  */
314 
315 void
pungetc(void)316 pungetc(void)
317 {
318 	parsefile->unget++;
319 }
320 
321 /*
322  * Push a string back onto the input at this current parsefile level.
323  * We handle aliases this way.
324  */
325 void
pushstring(char * s,void * ap)326 pushstring(char *s, void *ap)
327 {
328 	struct strpush *sp;
329 	size_t len;
330 
331 	len = strlen(s);
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 = parsefile->nextc;
341 	sp->prevnleft = parsefile->nleft;
342 	sp->unget = parsefile->unget;
343 	memcpy(sp->lastc, parsefile->lastc, sizeof(sp->lastc));
344 	sp->ap = (struct alias *)ap;
345 	if (ap) {
346 		((struct alias *)ap)->flag |= ALIASINUSE;
347 		sp->string = s;
348 	}
349 	parsefile->nextc = s;
350 	parsefile->nleft = len;
351 	parsefile->unget = 0;
352 	INTON;
353 }
354 
355 void
popstring(void)356 popstring(void)
357 {
358 	struct strpush *sp = parsefile->strpush;
359 
360 	INTOFF;
361 	if (sp->ap) {
362 		if (parsefile->nextc[-1] == ' ' ||
363 		    parsefile->nextc[-1] == '\t') {
364 			checkkwd |= CHKALIAS;
365 		}
366 		if (sp->string != sp->ap->val) {
367 			ckfree(sp->string);
368 		}
369 		sp->ap->flag &= ~ALIASINUSE;
370 		if (sp->ap->flag & ALIASDEAD) {
371 			unalias(sp->ap->name);
372 		}
373 	}
374 	parsefile->nextc = sp->prevstring;
375 	parsefile->nleft = sp->prevnleft;
376 	parsefile->unget = sp->unget;
377 	memcpy(parsefile->lastc, sp->lastc, sizeof(sp->lastc));
378 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
379 	parsefile->strpush = sp->prev;
380 	if (sp != &(parsefile->basestrpush))
381 		ckfree(sp);
382 	INTON;
383 }
384 
385 /*
386  * Set the input to take input from a file.  If push is set, push the
387  * old input onto the stack first.
388  */
389 
390 int
setinputfile(const char * fname,int flags)391 setinputfile(const char *fname, int flags)
392 {
393 	int fd;
394 
395 	INTOFF;
396 	if ((fd = open64(fname, O_RDONLY)) < 0) {
397 		if (flags & INPUT_NOFILE_OK)
398 			goto out;
399 		exitstatus = 127;
400 		exerror(EXERROR, "Can't open %s", fname);
401 	}
402 	if (fd < 10)
403 		fd = savefd(fd, fd);
404 	setinputfd(fd, flags & INPUT_PUSH_FILE);
405 out:
406 	INTON;
407 	return fd;
408 }
409 
410 
411 /*
412  * Like setinputfile, but takes an open file descriptor.  Call this with
413  * interrupts off.
414  */
415 
416 static void
setinputfd(int fd,int push)417 setinputfd(int fd, int push)
418 {
419 	if (push) {
420 		pushfile();
421 		parsefile->buf = 0;
422 	}
423 	parsefile->fd = fd;
424 	if (parsefile->buf == NULL)
425 		parsefile->buf = ckmalloc(IBUFSIZ);
426 	parsefile->lleft = parsefile->nleft = 0;
427 	plinno = 1;
428 }
429 
430 
431 /*
432  * Like setinputfile, but takes input from a string.
433  */
434 
435 void
setinputstring(char * string)436 setinputstring(char *string)
437 {
438 	INTOFF;
439 	pushfile();
440 	parsefile->nextc = string;
441 	parsefile->nleft = strlen(string);
442 	parsefile->buf = NULL;
443 	plinno = 1;
444 	INTON;
445 }
446 
447 
448 
449 /*
450  * To handle the "." command, a stack of input files is used.  Pushfile
451  * adds a new entry to the stack and popfile restores the previous level.
452  */
453 
454 STATIC void
pushfile(void)455 pushfile(void)
456 {
457 	struct parsefile *pf;
458 
459 	pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
460 	pf->prev = parsefile;
461 	pf->fd = -1;
462 	pf->strpush = NULL;
463 	pf->basestrpush.prev = NULL;
464 	pf->unget = 0;
465 	parsefile = pf;
466 }
467 
468 
469 void
popfile(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 	INTON;
484 }
485 
486 
unwindfiles(struct parsefile * stop)487 void unwindfiles(struct parsefile *stop)
488 {
489 	while (parsefile != stop)
490 		popfile();
491 }
492 
493 
494 /*
495  * Return to top level.
496  */
497 
498 void
popallfiles(void)499 popallfiles(void)
500 {
501 	unwindfiles(&basepf);
502 }
503