xref: /freebsd/bin/sh/input.c (revision a8445737e740901f5f2c8d24c12ef7fc8b00134e)
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 	"$Id$";
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 __P((void));
111 static int preadfd __P((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(line, len)
141 	char *line;
142 	int len;
143 {
144 	char *p = line;
145 	int nleft = len;
146 	int c;
147 
148 	while (--nleft > 0) {
149 		c = pgetc_macro();
150 		if (c == PEOF) {
151 			if (p == line)
152 				return NULL;
153 			break;
154 		}
155 		*p++ = c;
156 		if (c == '\n')
157 			break;
158 	}
159 	*p = '\0';
160 	return line;
161 }
162 
163 
164 
165 /*
166  * Read a character from the script, returning PEOF on end of file.
167  * Nul characters in the input are silently discarded.
168  */
169 
170 int
171 pgetc()
172 {
173 	return pgetc_macro();
174 }
175 
176 
177 static int
178 preadfd()
179 {
180 	int nr;
181 	parsenextc = parsefile->buf;
182 
183 retry:
184 #ifndef NO_HISTORY
185 	if (parsefile->fd == 0 && el) {
186 		const char *rl_cp;
187 
188 		rl_cp = el_gets(el, &nr);
189 		if (rl_cp == NULL)
190 			nr = 0;
191 		else {
192 			/* XXX - BUFSIZE should redesign so not necessary */
193 			(void) strcpy(parsenextc, rl_cp);
194 		}
195 	} else
196 #endif
197 		nr = read(parsefile->fd, parsenextc, BUFSIZ - 1);
198 
199 	if (nr <= 0) {
200                 if (nr < 0) {
201                         if (errno == EINTR)
202                                 goto retry;
203                         if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
204                                 int flags = fcntl(0, F_GETFL, 0);
205                                 if (flags >= 0 && flags & O_NONBLOCK) {
206                                         flags &=~ O_NONBLOCK;
207                                         if (fcntl(0, F_SETFL, flags) >= 0) {
208 						out2str("sh: turning off NDELAY mode\n");
209                                                 goto retry;
210                                         }
211                                 }
212                         }
213                 }
214                 nr = -1;
215 	}
216 	return nr;
217 }
218 
219 /*
220  * Refill the input buffer and return the next input character:
221  *
222  * 1) If a string was pushed back on the input, pop it;
223  * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
224  *    from a string so we can't refill the buffer, return EOF.
225  * 3) If there is more in this buffer, use it else call read to fill it.
226  * 4) Process input up to the next newline, deleting nul characters.
227  */
228 
229 int
230 preadbuffer()
231 {
232 	char *p, *q;
233 	int more;
234 	int something;
235 	extern EditLine *el;
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 		INTOFF;
297 		history(hist, whichprompt == 1 ? H_ENTER : H_ADD, parsenextc);
298 		INTON;
299 	}
300 #endif
301 
302 	if (vflag) {
303 		out2str(parsenextc);
304 		flushout(out2);
305 	}
306 
307 	*q = savec;
308 
309 	return *parsenextc++;
310 }
311 
312 /*
313  * Undo the last call to pgetc.  Only one character may be pushed back.
314  * PEOF may be pushed back.
315  */
316 
317 void
318 pungetc() {
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(s, len, ap)
329 	char *s;
330 	int len;
331 	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()
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(fname, push)
379 	char *fname;
380 	int push;
381 {
382 	int fd;
383 	int fd2;
384 
385 	INTOFF;
386 	if ((fd = open(fname, O_RDONLY)) < 0)
387 		error("Can't open %s", fname);
388 	if (fd < 10) {
389 		fd2 = copyfd(fd, 10);
390 		close(fd);
391 		if (fd2 < 0)
392 			error("Out of file descriptors");
393 		fd = fd2;
394 	}
395 	setinputfd(fd, push);
396 	INTON;
397 }
398 
399 
400 /*
401  * Like setinputfile, but takes an open file descriptor.  Call this with
402  * interrupts off.
403  */
404 
405 void
406 setinputfd(fd, push)
407 	int fd, push;
408 {
409 	(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
410 	if (push) {
411 		pushfile();
412 		parsefile->buf = ckmalloc(BUFSIZ);
413 	}
414 	if (parsefile->fd > 0)
415 		close(parsefile->fd);
416 	parsefile->fd = fd;
417 	if (parsefile->buf == NULL)
418 		parsefile->buf = ckmalloc(BUFSIZ);
419 	parselleft = parsenleft = 0;
420 	plinno = 1;
421 }
422 
423 
424 /*
425  * Like setinputfile, but takes input from a string.
426  */
427 
428 void
429 setinputstring(string, push)
430 	char *string;
431 	int push;
432 	{
433 	INTOFF;
434 	if (push)
435 		pushfile();
436 	parsenextc = string;
437 	parselleft = parsenleft = strlen(string);
438 	parsefile->buf = NULL;
439 	plinno = 1;
440 	INTON;
441 }
442 
443 
444 
445 /*
446  * To handle the "." command, a stack of input files is used.  Pushfile
447  * adds a new entry to the stack and popfile restores the previous level.
448  */
449 
450 STATIC void
451 pushfile() {
452 	struct parsefile *pf;
453 
454 	parsefile->nleft = parsenleft;
455 	parsefile->lleft = parselleft;
456 	parsefile->nextc = parsenextc;
457 	parsefile->linno = plinno;
458 	pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
459 	pf->prev = parsefile;
460 	pf->fd = -1;
461 	pf->strpush = NULL;
462 	pf->basestrpush.prev = NULL;
463 	parsefile = pf;
464 }
465 
466 
467 void
468 popfile() {
469 	struct parsefile *pf = parsefile;
470 
471 	INTOFF;
472 	if (pf->fd >= 0)
473 		close(pf->fd);
474 	if (pf->buf)
475 		ckfree(pf->buf);
476 	while (pf->strpush)
477 		popstring();
478 	parsefile = pf->prev;
479 	ckfree(pf);
480 	parsenleft = parsefile->nleft;
481 	parselleft = parsefile->lleft;
482 	parsenextc = parsefile->nextc;
483 	plinno = parsefile->linno;
484 	INTON;
485 }
486 
487 
488 /*
489  * Return to top level.
490  */
491 
492 void
493 popallfiles() {
494 	while (parsefile != &basepf)
495 		popfile();
496 }
497 
498 
499 
500 /*
501  * Close the file(s) that the shell is reading commands from.  Called
502  * after a fork is done.
503  */
504 
505 void
506 closescript() {
507 	popallfiles();
508 	if (parsefile->fd > 0) {
509 		close(parsefile->fd);
510 		parsefile->fd = 0;
511 	}
512 }
513