input.c revision 199629
150477Speter/*-
240269Srnordier * Copyright (c) 1991, 1993
340326Srnordier *	The Regents of the University of California.  All rights reserved.
440326Srnordier *
540326Srnordier * This code is derived from software contributed to Berkeley by
640326Srnordier * Kenneth Almquist.
740326Srnordier *
840326Srnordier * Redistribution and use in source and binary forms, with or without
980751Sjhb * modification, are permitted provided that the following conditions
10104680Sphk * are met:
1140326Srnordier * 1. Redistributions of source code must retain the above copyright
1280751Sjhb *    notice, this list of conditions and the following disclaimer.
1380751Sjhb * 2. Redistributions in binary form must reproduce the above copyright
1448919Srnordier *    notice, this list of conditions and the following disclaimer in the
1562138Sjhb *    documentation and/or other materials provided with the distribution.
1648919Srnordier * 4. Neither the name of the University nor the names of its contributors
1742480Srnordier *    may be used to endorse or promote products derived from this software
1842480Srnordier *    without specific prior written permission.
1940541Srnordier *
2040541Srnordier * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2140269Srnordier * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2240269Srnordier * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2340269Srnordier * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2440269Srnordier * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2540269Srnordier * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2640269Srnordier * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27104673Sgreen * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2840269Srnordier * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29104683Sjhb * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3040269Srnordier * SUCH DAMAGE.
31107879Sphk */
32107879Sphk
33107879Sphk#ifndef lint
34108000Simp#if 0
35108000Simpstatic char sccsid[] = "@(#)input.c	8.3 (Berkeley) 6/9/95";
36104635Sphk#endif
3796327Sjhb#endif /* not lint */
38108000Simp#include <sys/cdefs.h>
39108149Sobrien__FBSDID("$FreeBSD: head/bin/sh/input.c 199629 2009-11-21 14:28:32Z jilles $");
4096327Sjhb
41107879Sphk#include <stdio.h>	/* defines BUFSIZ */
4297860Sphk#include <fcntl.h>
4396306Sobrien#include <errno.h>
4440269Srnordier#include <unistd.h>
4540269Srnordier#include <stdlib.h>
4640269Srnordier#include <string.h>
4740269Srnordier
48108000Simp/*
4940269Srnordier * This file implements the input routines used by the parser.
50109886Sphk */
5140269Srnordier
52109886Sphk#include "shell.h"
53109886Sphk#include "redir.h"
54109886Sphk#include "syntax.h"
5540269Srnordier#include "input.h"
5640308Srnordier#include "output.h"
5740269Srnordier#include "options.h"
5840269Srnordier#include "memalloc.h"
5940269Srnordier#include "error.h"
6040269Srnordier#include "alias.h"
6160821Sjhb#include "parser.h"
62104632Sphk#include "myhistedit.h"
63104632Sphk#include "trap.h"
6440269Srnordier
6597867Sphk#define EOF_NLEFT -99		/* value of parsenleft when EOF pushed back */
6696424Speter
6796424SpeterMKINIT
68108016Simpstruct strpush {
6996424Speter	struct strpush *prev;	/* preceding string on stack */
7096424Speter	char *prevstring;
7180751Sjhb	int prevnleft;
7280751Sjhb	int prevlleft;
73104673Sgreen	struct alias *ap;	/* if push was associated with an alias */
74104673Sgreen};
75104673Sgreen
76104673Sgreen/*
7780751Sjhb * The parsefile structure pointed to by the global variable parsefile
7859150Sjhb * contains information about the current file being read.
7940269Srnordier */
8040314Srnordier
8140314SrnordierMKINIT
8240314Srnordierstruct parsefile {
8340314Srnordier	struct parsefile *prev;	/* preceding file on stack */
8440269Srnordier	int linno;		/* current line */
8540269Srnordier	int fd;			/* file descriptor (or -1 if string) */
86107879Sphk	int nleft;		/* number of chars left in this line */
8740269Srnordier	int lleft;		/* number of lines left in this buffer */
8840269Srnordier	char *nextc;		/* next char in buffer */
8940308Srnordier	char *buf;		/* input buffer */
9040269Srnordier	struct strpush *strpush; /* for pushing strings at this level */
9140404Srnordier	struct strpush basestrpush; /* so pushing one is fast */
9240269Srnordier};
93104635Sphk
9440269Srnordier
9580751Sjhbint plinno = 1;			/* input line number */
9680751SjhbMKINIT int parsenleft;		/* copy of parsefile->nleft */
9740404SrnordierMKINIT int parselleft;		/* copy of parsefile->lleft */
9860821Sjhbchar *parsenextc;		/* copy of parsefile->nextc */
9960821SjhbMKINIT struct parsefile basepf;	/* top level input file */
10060821Sjhbchar basebuf[BUFSIZ];		/* buffer for top level input file */
10160821SjhbSTATIC struct parsefile *parsefile = &basepf;	/* current input file */
10240404Srnordierint init_editline = 0;		/* editline library initialized? */
10340326Srnordierint whichprompt;		/* 1 == PS1, 2 == PS2 */
104100872Sru
105109886SphkEditLine *el;			/* cookie for editline package */
106109886Sphk
10740326SrnordierSTATIC void pushfile(void);
108100872Srustatic int preadfd(void);
10940326Srnordier
11040326Srnordier#ifdef mkinit
11140326SrnordierINCLUDE "input.h"
112INCLUDE "error.h"
113
114INIT {
115	extern char basebuf[];
116
117	basepf.nextc = basepf.buf = basebuf;
118}
119
120RESET {
121	popallfiles();
122	if (exception != EXSHELLPROC)
123		parselleft = parsenleft = 0;	/* clear input buffer */
124}
125
126SHELLPROC {
127	popallfiles();
128}
129#endif
130
131
132/*
133 * Read a line from the script.
134 */
135
136char *
137pfgets(char *line, int len)
138{
139	char *p = line;
140	int nleft = len;
141	int c;
142
143	while (--nleft > 0) {
144		c = pgetc_macro();
145		if (c == PEOF) {
146			if (p == line)
147				return NULL;
148			break;
149		}
150		*p++ = c;
151		if (c == '\n')
152			break;
153	}
154	*p = '\0';
155	return line;
156}
157
158
159
160/*
161 * Read a character from the script, returning PEOF on end of file.
162 * Nul characters in the input are silently discarded.
163 */
164
165int
166pgetc(void)
167{
168	return pgetc_macro();
169}
170
171
172static int
173preadfd(void)
174{
175	int nr;
176	parsenextc = parsefile->buf;
177
178#ifndef NO_HISTORY
179	if (el != NULL && gotwinch) {
180		gotwinch = 0;
181		el_resize(el);
182	}
183#endif
184retry:
185#ifndef NO_HISTORY
186	if (parsefile->fd == 0 && el) {
187		static const char *rl_cp;
188		static int el_len;
189
190		if (rl_cp == NULL)
191			rl_cp = el_gets(el, &el_len);
192		if (rl_cp == NULL)
193			nr = 0;
194		else {
195			nr = el_len;
196			if (nr > BUFSIZ - 1)
197				nr = BUFSIZ - 1;
198			memcpy(parsenextc, rl_cp, nr);
199			if (nr != el_len) {
200				el_len -= nr;
201				rl_cp += nr;
202			} else
203				rl_cp = NULL;
204		}
205	} else
206#endif
207		nr = read(parsefile->fd, parsenextc, BUFSIZ - 1);
208
209	if (nr <= 0) {
210                if (nr < 0) {
211                        if (errno == EINTR)
212                                goto retry;
213                        if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
214                                int flags = fcntl(0, F_GETFL, 0);
215                                if (flags >= 0 && flags & O_NONBLOCK) {
216                                        flags &=~ O_NONBLOCK;
217                                        if (fcntl(0, F_SETFL, flags) >= 0) {
218						out2fmt_flush("sh: turning off NDELAY mode\n");
219                                                goto retry;
220                                        }
221                                }
222                        }
223                }
224                nr = -1;
225	}
226	return nr;
227}
228
229/*
230 * Refill the input buffer and return the next input character:
231 *
232 * 1) If a string was pushed back on the input, pop it;
233 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
234 *    from a string so we can't refill the buffer, return EOF.
235 * 3) If there is more in this buffer, use it else call read to fill it.
236 * 4) Process input up to the next newline, deleting nul characters.
237 */
238
239int
240preadbuffer(void)
241{
242	char *p, *q;
243	int more;
244	int something;
245	char savec;
246
247	if (parsefile->strpush) {
248		popstring();
249		if (--parsenleft >= 0)
250			return (*parsenextc++);
251	}
252	if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
253		return PEOF;
254	flushout(&output);
255	flushout(&errout);
256
257again:
258	if (parselleft <= 0) {
259		if ((parselleft = preadfd()) == -1) {
260			parselleft = parsenleft = EOF_NLEFT;
261			return PEOF;
262		}
263	}
264
265	q = p = parsenextc;
266
267	/* delete nul characters */
268	something = 0;
269	for (more = 1; more;) {
270		switch (*p) {
271		case '\0':
272			p++;	/* Skip nul */
273			goto check;
274
275		case '\t':
276		case ' ':
277			break;
278
279		case '\n':
280			parsenleft = q - parsenextc;
281			more = 0; /* Stop processing here */
282			break;
283
284		default:
285			something = 1;
286			break;
287		}
288
289		*q++ = *p++;
290check:
291		if (--parselleft <= 0) {
292			parsenleft = q - parsenextc - 1;
293			if (parsenleft < 0)
294				goto again;
295			*q = '\0';
296			more = 0;
297		}
298	}
299
300	savec = *q;
301	*q = '\0';
302
303#ifndef NO_HISTORY
304	if (parsefile->fd == 0 && hist && something) {
305		HistEvent he;
306		INTOFF;
307		history(hist, &he, whichprompt == 1 ? H_ENTER : H_ADD,
308		    parsenextc);
309		INTON;
310	}
311#endif
312
313	if (vflag) {
314		out2str(parsenextc);
315		flushout(out2);
316	}
317
318	*q = savec;
319
320	return *parsenextc++;
321}
322
323/*
324 * Returns if we are certain we are at EOF. Does not cause any more input
325 * to be read from the outside world.
326 */
327
328int
329preadateof(void)
330{
331	if (parsenleft > 0)
332		return 0;
333	if (parsefile->strpush)
334		return 0;
335	if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
336		return 1;
337	return 0;
338}
339
340/*
341 * Undo the last call to pgetc.  Only one character may be pushed back.
342 * PEOF may be pushed back.
343 */
344
345void
346pungetc(void)
347{
348	parsenleft++;
349	parsenextc--;
350}
351
352/*
353 * Push a string back onto the input at this current parsefile level.
354 * We handle aliases this way.
355 */
356void
357pushstring(char *s, int len, void *ap)
358{
359	struct strpush *sp;
360
361	INTOFF;
362/*out2fmt_flush("*** calling pushstring: %s, %d\n", s, len);*/
363	if (parsefile->strpush) {
364		sp = ckmalloc(sizeof (struct strpush));
365		sp->prev = parsefile->strpush;
366		parsefile->strpush = sp;
367	} else
368		sp = parsefile->strpush = &(parsefile->basestrpush);
369	sp->prevstring = parsenextc;
370	sp->prevnleft = parsenleft;
371	sp->prevlleft = parselleft;
372	sp->ap = (struct alias *)ap;
373	if (ap)
374		((struct alias *)ap)->flag |= ALIASINUSE;
375	parsenextc = s;
376	parsenleft = len;
377	INTON;
378}
379
380void
381popstring(void)
382{
383	struct strpush *sp = parsefile->strpush;
384
385	INTOFF;
386	parsenextc = sp->prevstring;
387	parsenleft = sp->prevnleft;
388	parselleft = sp->prevlleft;
389/*out2fmt_flush("*** calling popstring: restoring to '%s'\n", parsenextc);*/
390	if (sp->ap)
391		sp->ap->flag &= ~ALIASINUSE;
392	parsefile->strpush = sp->prev;
393	if (sp != &(parsefile->basestrpush))
394		ckfree(sp);
395	INTON;
396}
397
398/*
399 * Set the input to take input from a file.  If push is set, push the
400 * old input onto the stack first.
401 */
402
403void
404setinputfile(char *fname, int push)
405{
406	int fd;
407	int fd2;
408
409	INTOFF;
410	if ((fd = open(fname, O_RDONLY)) < 0)
411		error("Can't open %s: %s", fname, strerror(errno));
412	if (fd < 10) {
413		fd2 = fcntl(fd, F_DUPFD, 10);
414		close(fd);
415		if (fd2 < 0)
416			error("Out of file descriptors");
417		fd = fd2;
418	}
419	setinputfd(fd, push);
420	INTON;
421}
422
423
424/*
425 * Like setinputfile, but takes an open file descriptor.  Call this with
426 * interrupts off.
427 */
428
429void
430setinputfd(int fd, int push)
431{
432	(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
433	if (push) {
434		pushfile();
435		parsefile->buf = ckmalloc(BUFSIZ);
436	}
437	if (parsefile->fd > 0)
438		close(parsefile->fd);
439	parsefile->fd = fd;
440	if (parsefile->buf == NULL)
441		parsefile->buf = ckmalloc(BUFSIZ);
442	parselleft = parsenleft = 0;
443	plinno = 1;
444}
445
446
447/*
448 * Like setinputfile, but takes input from a string.
449 */
450
451void
452setinputstring(char *string, int push)
453{
454	INTOFF;
455	if (push)
456		pushfile();
457	parsenextc = string;
458	parselleft = parsenleft = strlen(string);
459	parsefile->buf = NULL;
460	plinno = 1;
461	INTON;
462}
463
464
465
466/*
467 * To handle the "." command, a stack of input files is used.  Pushfile
468 * adds a new entry to the stack and popfile restores the previous level.
469 */
470
471STATIC void
472pushfile(void)
473{
474	struct parsefile *pf;
475
476	parsefile->nleft = parsenleft;
477	parsefile->lleft = parselleft;
478	parsefile->nextc = parsenextc;
479	parsefile->linno = plinno;
480	pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
481	pf->prev = parsefile;
482	pf->fd = -1;
483	pf->strpush = NULL;
484	pf->basestrpush.prev = NULL;
485	parsefile = pf;
486}
487
488
489void
490popfile(void)
491{
492	struct parsefile *pf = parsefile;
493
494	INTOFF;
495	if (pf->fd >= 0)
496		close(pf->fd);
497	if (pf->buf)
498		ckfree(pf->buf);
499	while (pf->strpush)
500		popstring();
501	parsefile = pf->prev;
502	ckfree(pf);
503	parsenleft = parsefile->nleft;
504	parselleft = parsefile->lleft;
505	parsenextc = parsefile->nextc;
506	plinno = parsefile->linno;
507	INTON;
508}
509
510
511/*
512 * Return to top level.
513 */
514
515void
516popallfiles(void)
517{
518	while (parsefile != &basepf)
519		popfile();
520}
521
522
523
524/*
525 * Close the file(s) that the shell is reading commands from.  Called
526 * after a fork is done.
527 */
528
529void
530closescript(void)
531{
532	popallfiles();
533	if (parsefile->fd > 0) {
534		close(parsefile->fd);
535		parsefile->fd = 0;
536	}
537}
538