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