Home | History | Annotate | Line # | Download | only in sh
input.c revision 1.56.2.2
      1 /*	$NetBSD: input.c,v 1.56.2.2 2017/08/09 05:35:18 snj 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. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 #ifndef lint
     37 #if 0
     38 static char sccsid[] = "@(#)input.c	8.3 (Berkeley) 6/9/95";
     39 #else
     40 __RCSID("$NetBSD: input.c,v 1.56.2.2 2017/08/09 05:35:18 snj Exp $");
     41 #endif
     42 #endif /* not lint */
     43 
     44 #include <stdio.h>	/* defines BUFSIZ */
     45 #include <fcntl.h>
     46 #include <errno.h>
     47 #include <unistd.h>
     48 #include <limits.h>
     49 #include <stdlib.h>
     50 #include <string.h>
     51 #include <sys/stat.h>
     52 
     53 /*
     54  * This file implements the input routines used by the parser.
     55  */
     56 
     57 #include "shell.h"
     58 #include "redir.h"
     59 #include "syntax.h"
     60 #include "input.h"
     61 #include "output.h"
     62 #include "options.h"
     63 #include "memalloc.h"
     64 #include "error.h"
     65 #include "alias.h"
     66 #include "parser.h"
     67 #include "myhistedit.h"
     68 #include "show.h"
     69 
     70 #define EOF_NLEFT -99		/* value of parsenleft when EOF pushed back */
     71 
     72 MKINIT
     73 struct strpush {
     74 	struct strpush *prev;	/* preceding string on stack */
     75 	const char *prevstring;
     76 	int prevnleft;
     77 	int prevlleft;
     78 	struct alias *ap;	/* if push was associated with an alias */
     79 };
     80 
     81 /*
     82  * The parsefile structure pointed to by the global variable parsefile
     83  * contains information about the current file being read.
     84  */
     85 
     86 MKINIT
     87 struct parsefile {
     88 	struct parsefile *prev;	/* preceding file on stack */
     89 	int linno;		/* current line */
     90 	int fd;			/* file descriptor (or -1 if string) */
     91 	int nleft;		/* number of chars left in this line */
     92 	int lleft;		/* number of chars left in this buffer */
     93 	const char *nextc;	/* next char in buffer */
     94 	char *buf;		/* input buffer */
     95 	struct strpush *strpush; /* for pushing strings at this level */
     96 	struct strpush basestrpush; /* so pushing one is fast */
     97 };
     98 
     99 
    100 int plinno = 1;			/* input line number */
    101 int parsenleft;			/* copy of parsefile->nleft */
    102 MKINIT int parselleft;		/* copy of parsefile->lleft */
    103 const char *parsenextc;		/* copy of parsefile->nextc */
    104 MKINIT struct parsefile basepf;	/* top level input file */
    105 MKINIT char basebuf[BUFSIZ];	/* buffer for top level input file */
    106 struct parsefile *parsefile = &basepf;	/* current input file */
    107 int init_editline = 0;		/* editline library initialized? */
    108 int whichprompt;		/* 1 == PS1, 2 == PS2 */
    109 
    110 STATIC void pushfile(void);
    111 static int preadfd(void);
    112 
    113 #ifdef mkinit
    114 INCLUDE <stdio.h>
    115 INCLUDE "input.h"
    116 INCLUDE "error.h"
    117 
    118 INIT {
    119 	basepf.nextc = basepf.buf = basebuf;
    120 }
    121 
    122 RESET {
    123 	if (exception != EXSHELLPROC)
    124 		parselleft = parsenleft = 0;	/* clear input buffer */
    125 	popallfiles();
    126 }
    127 
    128 SHELLPROC {
    129 	popallfiles();
    130 }
    131 #endif
    132 
    133 
    134 #if 0		/* this is unused */
    135 /*
    136  * Read a line from the script.
    137  */
    138 
    139 char *
    140 pfgets(char *line, int len)
    141 {
    142 	char *p = line;
    143 	int nleft = len;
    144 	int c;
    145 
    146 	while (--nleft > 0) {
    147 		c = pgetc_macro();
    148 		if (c == PEOF) {
    149 			if (p == line)
    150 				return NULL;
    151 			break;
    152 		}
    153 		*p++ = c;
    154 		if (c == '\n')
    155 			break;
    156 	}
    157 	*p = '\0';
    158 	return line;
    159 }
    160 #endif
    161 
    162 
    163 /*
    164  * Read a character from the script, returning PEOF on end of file.
    165  * Nul characters in the input are silently discarded.
    166  */
    167 
    168 int
    169 pgetc(void)
    170 {
    171 	return pgetc_macro();
    172 }
    173 
    174 
    175 static int
    176 preadfd(void)
    177 {
    178 	int nr;
    179 	char *buf =  parsefile->buf;
    180 	parsenextc = buf;
    181 
    182  retry:
    183 #ifndef SMALL
    184 	if (parsefile->fd == 0 && el) {
    185 		static const char *rl_cp;
    186 		static int el_len;
    187 
    188 		if (rl_cp == NULL)
    189 			rl_cp = el_gets(el, &el_len);
    190 		if (rl_cp == NULL)
    191 			nr = el_len == 0 ? 0 : -1;
    192 		else {
    193 			nr = el_len;
    194 			if (nr > BUFSIZ - 8)
    195 				nr = BUFSIZ - 8;
    196 			memcpy(buf, rl_cp, nr);
    197 			if (nr != el_len) {
    198 				el_len -= nr;
    199 				rl_cp += nr;
    200 			} else
    201 				rl_cp = 0;
    202 		}
    203 
    204 	} else
    205 #endif
    206 		nr = read(parsefile->fd, buf, BUFSIZ - 8);
    207 
    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 
    216                                 if (flags >= 0 && flags & O_NONBLOCK) {
    217                                         flags &=~ O_NONBLOCK;
    218                                         if (fcntl(0, F_SETFL, flags) >= 0) {
    219 						out2str("sh: turning off NDELAY mode\n");
    220                                                 goto retry;
    221                                         }
    222                                 }
    223                         }
    224                 }
    225                 nr = -1;
    226 	}
    227 	return nr;
    228 }
    229 
    230 /*
    231  * Refill the input buffer and return the next input character:
    232  *
    233  * 1) If a string was pushed back on the input, pop it;
    234  * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
    235  *    from a string so we can't refill the buffer, return EOF.
    236  * 3) If the is more stuff in this buffer, use it else call read to fill it.
    237  * 4) Process input up to the next newline, deleting nul characters.
    238  */
    239 
    240 int
    241 preadbuffer(void)
    242 {
    243 	char *p, *q;
    244 	int more;
    245 #ifndef SMALL
    246 	int something;
    247 #endif
    248 	char savec;
    249 
    250 	while (parsefile->strpush) {
    251 		popstring();
    252 		if (--parsenleft >= 0)
    253 			return (*parsenextc++);
    254 	}
    255 	if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
    256 		return PEOF;
    257 	flushout(&output);
    258 	flushout(&errout);
    259 
    260  again:
    261 	if (parselleft <= 0) {
    262 		if ((parselleft = preadfd()) == -1) {
    263 			parselleft = parsenleft = EOF_NLEFT;
    264 			return PEOF;
    265 		}
    266 	}
    267 
    268 		/* p = (not const char *)parsenextc; */
    269 	p = parsefile->buf + (parsenextc - parsefile->buf);
    270 	q = p;
    271 
    272 	/* delete nul characters */
    273 #ifndef SMALL
    274 	something = 0;
    275 #endif
    276 	for (more = 1; more;) {
    277 		switch (*p) {
    278 		case '\0':
    279 			p++;	/* Skip nul */
    280 			goto check;
    281 
    282 		case '\t':
    283 		case ' ':
    284 			break;
    285 
    286 		case '\n':
    287 			parsenleft = q - parsenextc;
    288 			more = 0; /* Stop processing here */
    289 			break;
    290 
    291 		default:
    292 #ifndef SMALL
    293 			something = 1;
    294 #endif
    295 			break;
    296 		}
    297 
    298 		*q++ = *p++;
    299  check:
    300 		if (--parselleft <= 0) {
    301 			parsenleft = q - parsenextc - 1;
    302 			if (parsenleft < 0)
    303 				goto again;
    304 			*q = '\0';
    305 			more = 0;
    306 		}
    307 	}
    308 
    309 	savec = *q;
    310 	*q = '\0';
    311 
    312 #ifndef SMALL
    313 	if (parsefile->fd == 0 && hist && (something || whichprompt == 2)) {
    314 		HistEvent he;
    315 
    316 		INTOFF;
    317 		history(hist, &he, whichprompt != 2 ? H_ENTER : H_APPEND,
    318 		    parsenextc);
    319 		INTON;
    320 	}
    321 #endif
    322 
    323 	if (vflag) {
    324 		out2str(parsenextc);
    325 		flushout(out2);
    326 	}
    327 
    328 	*q = savec;
    329 
    330 	return *parsenextc++;
    331 }
    332 
    333 /*
    334  * Undo the last call to pgetc.  Only one character may be pushed back.
    335  * PEOF may be pushed back.
    336  */
    337 
    338 void
    339 pungetc(void)
    340 {
    341 	parsenleft++;
    342 	parsenextc--;
    343 }
    344 
    345 /*
    346  * Push a string back onto the input at this current parsefile level.
    347  * We handle aliases this way.
    348  */
    349 void
    350 pushstring(const char *s, int len, struct alias *ap)
    351 {
    352 	struct strpush *sp;
    353 
    354 	VTRACE(DBG_INPUT,
    355 	    ("pushstring(\"%.*s\", %d)%s%s%s had: nl=%d ll=%d \"%.*s\"\n",
    356 	    len, s, len, ap ? " for alias:'" : "",
    357 	    ap ? ap->name : "", ap ? "'" : "",
    358 	    parsenleft, parselleft, parsenleft, parsenextc));
    359 
    360 	INTOFF;
    361 	if (parsefile->strpush) {
    362 		sp = ckmalloc(sizeof (struct strpush));
    363 		sp->prev = parsefile->strpush;
    364 		parsefile->strpush = sp;
    365 	} else
    366 		sp = parsefile->strpush = &(parsefile->basestrpush);
    367 
    368 	sp->prevstring = parsenextc;
    369 	sp->prevnleft = parsenleft;
    370 	sp->prevlleft = parselleft;
    371 	sp->ap = ap;
    372 	if (ap)
    373 		ap->flag |= ALIASINUSE;
    374 	parsenextc = s;
    375 	parsenleft = len;
    376 	INTON;
    377 }
    378 
    379 void
    380 popstring(void)
    381 {
    382 	struct strpush *sp = parsefile->strpush;
    383 
    384 	INTOFF;
    385 	parsenextc = sp->prevstring;
    386 	parsenleft = sp->prevnleft;
    387 	parselleft = sp->prevlleft;
    388 
    389 	VTRACE(DBG_INPUT, ("popstring()%s%s%s nl=%d ll=%d \"%.*s\"\n",
    390 	    sp->ap ? " from alias:'" : "", sp->ap ? sp->ap->name : "",
    391 	    sp->ap ? "'" : "", parsenleft, parselleft, parsenleft, parsenextc));
    392 
    393 	if (sp->ap)
    394 		sp->ap->flag &= ~ALIASINUSE;
    395 	parsefile->strpush = sp->prev;
    396 	if (sp != &(parsefile->basestrpush))
    397 		ckfree(sp);
    398 	INTON;
    399 }
    400 
    401 /*
    402  * Set the input to take input from a file.  If push is set, push the
    403  * old input onto the stack first.
    404  */
    405 
    406 void
    407 setinputfile(const char *fname, int push)
    408 {
    409 	unsigned char magic[4];
    410 	int fd;
    411 	int fd2;
    412 	struct stat sb;
    413 
    414 	CTRACE(DBG_INPUT,("setinputfile(\"%s\", %spush)\n",fname,push?"":"no"));
    415 
    416 	INTOFF;
    417 	if ((fd = open(fname, O_RDONLY)) < 0)
    418 		error("Can't open %s", fname);
    419 
    420 	/* Since the message "Syntax error: "(" unexpected" is not very
    421 	 * helpful, we check if the file starts with the ELF magic to
    422 	 * avoid that message. The first lseek tries to make sure that
    423 	 * we can later rewind the file.
    424 	 */
    425 	if (fstat(fd, &sb) == 0 && S_ISREG(sb.st_mode) &&
    426 	    lseek(fd, 0, SEEK_SET) == 0) {
    427 		if (read(fd, magic, 4) == 4) {
    428 			if (memcmp(magic, "\177ELF", 4) == 0) {
    429 				(void)close(fd);
    430 				error("Cannot execute ELF binary %s", fname);
    431 			}
    432 		}
    433 		if (lseek(fd, 0, SEEK_SET) != 0) {
    434 			(void)close(fd);
    435 			error("Cannot rewind the file %s", fname);
    436 		}
    437 	}
    438 
    439 	fd2 = to_upper_fd(fd);	/* closes fd, returns higher equiv */
    440 	if (fd2 == fd) {
    441 		(void) close(fd);
    442 		error("Out of file descriptors");
    443 	}
    444 
    445 	setinputfd(fd2, push);
    446 	INTON;
    447 }
    448 
    449 /*
    450  * When a shell fd needs to be altered (when the user wants to use
    451  * the same fd - rare, but happens - we need to locate the ref to
    452  * the fd, and update it.  This happens via a callback.
    453  * This is the callback func for fd's used for shell input
    454  */
    455 static void
    456 input_fd_swap(int from, int to)
    457 {
    458 	struct parsefile *pf;
    459 
    460 	pf = parsefile;
    461 	while (pf != NULL) {		/* don't need to stop at basepf */
    462 		if (pf->fd == from)
    463 			pf->fd = to;
    464 		pf = pf->prev;
    465 	}
    466 }
    467 
    468 /*
    469  * Like setinputfile, but takes an open file descriptor.  Call this with
    470  * interrupts off.
    471  */
    472 
    473 void
    474 setinputfd(int fd, int push)
    475 {
    476 	VTRACE(DBG_INPUT, ("setinputfd(%d, %spush)\n", fd, push?"":"no"));
    477 
    478 	register_sh_fd(fd, input_fd_swap);
    479 	(void) fcntl(fd, F_SETFD, FD_CLOEXEC);
    480 	if (push)
    481 		pushfile();
    482 	if (parsefile->fd > 0)
    483 		sh_close(parsefile->fd);
    484 	parsefile->fd = fd;
    485 	if (parsefile->buf == NULL)
    486 		parsefile->buf = ckmalloc(BUFSIZ);
    487 	parselleft = parsenleft = 0;
    488 	plinno = 1;
    489 
    490 	CTRACE(DBG_INPUT, ("setinputfd(%d, %spush) done; plinno=1\n", fd,
    491 	    push ? "" : "no"));
    492 }
    493 
    494 
    495 /*
    496  * Like setinputfile, but takes input from a string.
    497  */
    498 
    499 void
    500 setinputstring(char *string, int push, int line1)
    501 {
    502 
    503 	INTOFF;
    504 	if (push)		/* XXX: always, as it happens */
    505 		pushfile();
    506 	parsenextc = string;
    507 	parselleft = parsenleft = strlen(string);
    508 	plinno = line1;
    509 
    510 	CTRACE(DBG_INPUT,
    511 	    ("setinputstring(\"%.20s%s\" (%d), %push, @ %d)\n", string,
    512 	    (parsenleft > 20 ? "..." : ""), parsenleft, push?"":"no", line1));
    513 	INTON;
    514 }
    515 
    516 
    517 
    518 /*
    519  * To handle the "." command, a stack of input files is used.  Pushfile
    520  * adds a new entry to the stack and popfile restores the previous level.
    521  */
    522 
    523 STATIC void
    524 pushfile(void)
    525 {
    526 	struct parsefile *pf;
    527 
    528 	VTRACE(DBG_INPUT,
    529 	    ("pushfile(): fd=%d buf=%p nl=%d ll=%d \"%.*s\" plinno=%d\n",
    530 	    parsefile->fd, parsefile->buf, parsenleft, parselleft,
    531 	    parsenleft, parsenextc, plinno));
    532 
    533 	parsefile->nleft = parsenleft;
    534 	parsefile->lleft = parselleft;
    535 	parsefile->nextc = parsenextc;
    536 	parsefile->linno = plinno;
    537 	pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
    538 	pf->prev = parsefile;
    539 	pf->fd = -1;
    540 	pf->strpush = NULL;
    541 	pf->basestrpush.prev = NULL;
    542 	pf->buf = NULL;
    543 	parsefile = pf;
    544 }
    545 
    546 
    547 void
    548 popfile(void)
    549 {
    550 	struct parsefile *pf = parsefile;
    551 
    552 	INTOFF;
    553 	if (pf->fd >= 0)
    554 		sh_close(pf->fd);
    555 	if (pf->buf)
    556 		ckfree(pf->buf);
    557 	while (pf->strpush)
    558 		popstring();
    559 	parsefile = pf->prev;
    560 	ckfree(pf);
    561 	parsenleft = parsefile->nleft;
    562 	parselleft = parsefile->lleft;
    563 	parsenextc = parsefile->nextc;
    564 
    565 	VTRACE(DBG_INPUT,
    566 	    ("popfile(): fd=%d buf=%p nl=%d ll=%d \"%.*s\" plinno:%d->%d\n",
    567 	    parsefile->fd, parsefile->buf, parsenleft, parselleft,
    568 	    parsenleft, parsenextc, plinno, parsefile->linno));
    569 
    570 	plinno = parsefile->linno;
    571 	INTON;
    572 }
    573 
    574 /*
    575  * Return current file (to go back to it later using popfilesupto()).
    576  */
    577 
    578 struct parsefile *
    579 getcurrentfile(void)
    580 {
    581 	return parsefile;
    582 }
    583 
    584 
    585 /*
    586  * Pop files until the given file is on top again. Useful for regular
    587  * builtins that read shell commands from files or strings.
    588  * If the given file is not an active file, an error is raised.
    589  */
    590 
    591 void
    592 popfilesupto(struct parsefile *file)
    593 {
    594 	while (parsefile != file && parsefile != &basepf)
    595 		popfile();
    596 	if (parsefile != file)
    597 		error("popfilesupto() misused");
    598 }
    599 
    600 
    601 /*
    602  * Return to top level.
    603  */
    604 
    605 void
    606 popallfiles(void)
    607 {
    608 	while (parsefile != &basepf)
    609 		popfile();
    610 }
    611 
    612 
    613 
    614 /*
    615  * Close the file(s) that the shell is reading commands from.  Called
    616  * after a fork is done.
    617  *
    618  * Takes one arg, vfork, which tells it to not modify its global vars
    619  * as it is still running in the parent.
    620  *
    621  * This code is (probably) unnecessary as the 'close on exec' flag is
    622  * set and should be enough.  In the vfork case it is definitely wrong
    623  * to close the fds as another fork() may be done later to feed data
    624  * from a 'here' document into a pipe and we don't want to close the
    625  * pipe!
    626  */
    627 
    628 void
    629 closescript(int vforked)
    630 {
    631 	if (vforked)
    632 		return;
    633 	popallfiles();
    634 	if (parsefile->fd > 0) {
    635 		sh_close(parsefile->fd);
    636 		parsefile->fd = 0;
    637 	}
    638 }
    639