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