Home | History | Annotate | Line # | Download | only in sh
input.c revision 1.60
      1 /*	$NetBSD: input.c,v 1.60 2017/07/05 19:54:21 kre 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.60 2017/07/05 19:54:21 kre 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) {
    314 		HistEvent he;
    315 		INTOFF;
    316 		history(hist, &he, whichprompt == 1? H_ENTER : H_APPEND,
    317 		    parsenextc);
    318 		INTON;
    319 	}
    320 #endif
    321 
    322 	if (vflag) {
    323 		out2str(parsenextc);
    324 		flushout(out2);
    325 	}
    326 
    327 	*q = savec;
    328 
    329 	return *parsenextc++;
    330 }
    331 
    332 /*
    333  * Undo the last call to pgetc.  Only one character may be pushed back.
    334  * PEOF may be pushed back.
    335  */
    336 
    337 void
    338 pungetc(void)
    339 {
    340 	parsenleft++;
    341 	parsenextc--;
    342 }
    343 
    344 /*
    345  * Push a string back onto the input at this current parsefile level.
    346  * We handle aliases this way.
    347  */
    348 void
    349 pushstring(const char *s, int len, struct alias *ap)
    350 {
    351 	struct strpush *sp;
    352 
    353 	VTRACE(DBG_INPUT,
    354 	    ("pushstring(\"%.*s\", %d)%s%s%s had: nl=%d ll=%d \"%.*s\"\n",
    355 	    len, s, len, ap ? " for alias:'" : "",
    356 	    ap ? ap->name : "", ap ? "'" : "",
    357 	    parsenleft, parselleft, parsenleft, parsenextc));
    358 
    359 	INTOFF;
    360 	if (parsefile->strpush) {
    361 		sp = ckmalloc(sizeof (struct strpush));
    362 		sp->prev = parsefile->strpush;
    363 		parsefile->strpush = sp;
    364 	} else
    365 		sp = parsefile->strpush = &(parsefile->basestrpush);
    366 
    367 	sp->prevstring = parsenextc;
    368 	sp->prevnleft = parsenleft;
    369 	sp->prevlleft = parselleft;
    370 	sp->ap = ap;
    371 	if (ap)
    372 		ap->flag |= ALIASINUSE;
    373 	parsenextc = s;
    374 	parsenleft = len;
    375 	INTON;
    376 }
    377 
    378 void
    379 popstring(void)
    380 {
    381 	struct strpush *sp = parsefile->strpush;
    382 
    383 	INTOFF;
    384 	parsenextc = sp->prevstring;
    385 	parsenleft = sp->prevnleft;
    386 	parselleft = sp->prevlleft;
    387 
    388 	VTRACE(DBG_INPUT, ("popstring()%s%s%s nl=%d ll=%d \"%.*s\"\n",
    389 	    sp->ap ? " from alias:'" : "", sp->ap ? sp->ap->name : "",
    390 	    sp->ap ? "'" : "", parsenleft, parselleft, parsenleft, parsenextc));
    391 
    392 	if (sp->ap)
    393 		sp->ap->flag &= ~ALIASINUSE;
    394 	parsefile->strpush = sp->prev;
    395 	if (sp != &(parsefile->basestrpush))
    396 		ckfree(sp);
    397 	INTON;
    398 }
    399 
    400 /*
    401  * Set the input to take input from a file.  If push is set, push the
    402  * old input onto the stack first.
    403  */
    404 
    405 void
    406 setinputfile(const char *fname, int push)
    407 {
    408 	unsigned char magic[4];
    409 	int fd;
    410 	int fd2;
    411 	struct stat sb;
    412 
    413 	CTRACE(DBG_INPUT,("setinputfile(\"%s\", %spush)\n",fname,push?"":"no"));
    414 
    415 	INTOFF;
    416 	if ((fd = open(fname, O_RDONLY)) < 0)
    417 		error("Can't open %s", fname);
    418 
    419 	/* Since the message "Syntax error: "(" unexpected" is not very
    420 	 * helpful, we check if the file starts with the ELF magic to
    421 	 * avoid that message. The first lseek tries to make sure that
    422 	 * we can later rewind the file.
    423 	 */
    424 	if (fstat(fd, &sb) == 0 && S_ISREG(sb.st_mode) &&
    425 	    lseek(fd, 0, SEEK_SET) == 0) {
    426 		if (read(fd, magic, 4) == 4) {
    427 			if (memcmp(magic, "\177ELF", 4) == 0) {
    428 				(void)close(fd);
    429 				error("Cannot execute ELF binary %s", fname);
    430 			}
    431 		}
    432 		if (lseek(fd, 0, SEEK_SET) != 0) {
    433 			(void)close(fd);
    434 			error("Cannot rewind the file %s", fname);
    435 		}
    436 	}
    437 
    438 	fd2 = to_upper_fd(fd);	/* closes fd, returns higher equiv */
    439 	if (fd2 == fd) {
    440 		(void) close(fd);
    441 		error("Out of file descriptors");
    442 	}
    443 
    444 	setinputfd(fd2, push);
    445 	INTON;
    446 }
    447 
    448 /*
    449  * When a shell fd needs to be altered (when the user wants to use
    450  * the same fd - rare, but happens - we need to locate the ref to
    451  * the fd, and update it.  This happens via a callback.
    452  * This is the callback func for fd's used for shell input
    453  */
    454 static void
    455 input_fd_swap(int from, int to)
    456 {
    457 	struct parsefile *pf;
    458 
    459 	pf = parsefile;
    460 	while (pf != NULL) {		/* don't need to stop at basepf */
    461 		if (pf->fd == from)
    462 			pf->fd = to;
    463 		pf = pf->prev;
    464 	}
    465 }
    466 
    467 /*
    468  * Like setinputfile, but takes an open file descriptor.  Call this with
    469  * interrupts off.
    470  */
    471 
    472 void
    473 setinputfd(int fd, int push)
    474 {
    475 	VTRACE(DBG_INPUT, ("setinputfd(%d, %spush)\n", fd, push?"":"no"));
    476 
    477 	register_sh_fd(fd, input_fd_swap);
    478 	(void) fcntl(fd, F_SETFD, FD_CLOEXEC);
    479 	if (push)
    480 		pushfile();
    481 	if (parsefile->fd > 0)
    482 		sh_close(parsefile->fd);
    483 	parsefile->fd = fd;
    484 	if (parsefile->buf == NULL)
    485 		parsefile->buf = ckmalloc(BUFSIZ);
    486 	parselleft = parsenleft = 0;
    487 	plinno = 1;
    488 
    489 	CTRACE(DBG_INPUT, ("setinputfd(%d, %spush) done; plinno=1\n", fd,
    490 	    push ? "" : "no"));
    491 }
    492 
    493 
    494 /*
    495  * Like setinputfile, but takes input from a string.
    496  */
    497 
    498 void
    499 setinputstring(char *string, int push, int line1)
    500 {
    501 
    502 	INTOFF;
    503 	if (push)		/* XXX: always, as it happens */
    504 		pushfile();
    505 	parsenextc = string;
    506 	parselleft = parsenleft = strlen(string);
    507 	plinno = line1;
    508 
    509 	CTRACE(DBG_INPUT,
    510 	    ("setinputstring(\"%.20s%s\" (%d), %push, @ %d)\n", string,
    511 	    (parsenleft > 20 ? "..." : ""), parsenleft, push?"":"no", line1));
    512 	INTON;
    513 }
    514 
    515 
    516 
    517 /*
    518  * To handle the "." command, a stack of input files is used.  Pushfile
    519  * adds a new entry to the stack and popfile restores the previous level.
    520  */
    521 
    522 STATIC void
    523 pushfile(void)
    524 {
    525 	struct parsefile *pf;
    526 
    527 	VTRACE(DBG_INPUT,
    528 	    ("pushfile(): fd=%d buf=%p nl=%d ll=%d \"%.*s\" plinno=%d\n",
    529 	    parsefile->fd, parsefile->buf, parsenleft, parselleft,
    530 	    parsenleft, parsenextc, plinno));
    531 
    532 	parsefile->nleft = parsenleft;
    533 	parsefile->lleft = parselleft;
    534 	parsefile->nextc = parsenextc;
    535 	parsefile->linno = plinno;
    536 	pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
    537 	pf->prev = parsefile;
    538 	pf->fd = -1;
    539 	pf->strpush = NULL;
    540 	pf->basestrpush.prev = NULL;
    541 	pf->buf = NULL;
    542 	parsefile = pf;
    543 }
    544 
    545 
    546 void
    547 popfile(void)
    548 {
    549 	struct parsefile *pf = parsefile;
    550 
    551 	INTOFF;
    552 	if (pf->fd >= 0)
    553 		sh_close(pf->fd);
    554 	if (pf->buf)
    555 		ckfree(pf->buf);
    556 	while (pf->strpush)
    557 		popstring();
    558 	parsefile = pf->prev;
    559 	ckfree(pf);
    560 	parsenleft = parsefile->nleft;
    561 	parselleft = parsefile->lleft;
    562 	parsenextc = parsefile->nextc;
    563 
    564 	VTRACE(DBG_INPUT,
    565 	    ("popfile(): fd=%d buf=%p nl=%d ll=%d \"%.*s\" plinno:%d->%d\n",
    566 	    parsefile->fd, parsefile->buf, parsenleft, parselleft,
    567 	    parsenleft, parsenextc, plinno, parsefile->linno));
    568 
    569 	plinno = parsefile->linno;
    570 	INTON;
    571 }
    572 
    573 /*
    574  * Return current file (to go back to it later using popfilesupto()).
    575  */
    576 
    577 struct parsefile *
    578 getcurrentfile(void)
    579 {
    580 	return parsefile;
    581 }
    582 
    583 
    584 /*
    585  * Pop files until the given file is on top again. Useful for regular
    586  * builtins that read shell commands from files or strings.
    587  * If the given file is not an active file, an error is raised.
    588  */
    589 
    590 void
    591 popfilesupto(struct parsefile *file)
    592 {
    593 	while (parsefile != file && parsefile != &basepf)
    594 		popfile();
    595 	if (parsefile != file)
    596 		error("popfilesupto() misused");
    597 }
    598 
    599 
    600 /*
    601  * Return to top level.
    602  */
    603 
    604 void
    605 popallfiles(void)
    606 {
    607 	while (parsefile != &basepf)
    608 		popfile();
    609 }
    610 
    611 
    612 
    613 /*
    614  * Close the file(s) that the shell is reading commands from.  Called
    615  * after a fork is done.
    616  *
    617  * Takes one arg, vfork, which tells it to not modify its global vars
    618  * as it is still running in the parent.
    619  *
    620  * This code is (probably) unnecessary as the 'close on exec' flag is
    621  * set and should be enough.  In the vfork case it is definitely wrong
    622  * to close the fds as another fork() may be done later to feed data
    623  * from a 'here' document into a pipe and we don't want to close the
    624  * pipe!
    625  */
    626 
    627 void
    628 closescript(int vforked)
    629 {
    630 	if (vforked)
    631 		return;
    632 	popallfiles();
    633 	if (parsefile->fd > 0) {
    634 		sh_close(parsefile->fd);
    635 		parsefile->fd = 0;
    636 	}
    637 }
    638