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