1 /*        $NetBSD: input.c,v 1.76 2024/10/14 08:15:43 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.76 2024/10/14 08:15:43 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           int nskip;                    /* number of \0's dropped in previous line */
94           const char *nextc;  /* next char in buffer */
95           char *buf;                    /* input buffer */
96           struct strpush *strpush; /* for pushing strings at this level */
97           struct strpush basestrpush; /* so pushing one is fast */
98 };
99 
100 
101 int plinno = 1;                         /* input line number */
102 int parsenleft;                         /* copy of parsefile->nleft */
103 MKINIT int parselleft;                  /* copy of parsefile->lleft */
104 const char *parsenextc;                 /* copy of parsefile->nextc */
105 MKINIT struct parsefile basepf;         /* top level input file */
106 MKINIT char basebuf[BUFSIZ];  /* buffer for top level input file */
107 struct parsefile *parsefile = &basepf;  /* current input file */
108 int init_editline = 0;                  /* editline library initialized? */
109 int whichprompt;              /* 1 == PS1, 2 == PS2 */
110 
111 STATIC void pushfile(void);
112 static int preadfd(void);
113 
114 #ifdef mkinit
115 INCLUDE <stdio.h>
116 INCLUDE "input.h"
117 INCLUDE "error.h"
118 
119 INIT {
120           basepf.nextc = basepf.buf = basebuf;
121 }
122 
123 RESET {
124           if (exception != EXSHELLPROC)
125                     parselleft = parsenleft = 0;  /* clear input buffer */
126           popallfiles();
127 }
128 
129 SHELLPROC {
130           popallfiles();
131 }
132 #endif
133 
134 
135 #if 0               /* this is unused */
136 /*
137  * Read a line from the script.
138  */
139 
140 char *
141 pfgets(char *line, int len)
142 {
143           char *p = line;
144           int nleft = len;
145           int c;
146 
147           while (--nleft > 0) {
148                     c = pgetc_macro();
149                     if (c == PFAKE)               /* consecutive PFAKEs is impossible */
150                               c = pgetc_macro();
151                     if (c == PEOF) {
152                               if (p == line)
153                                         return NULL;
154                               break;
155                     }
156                     *p++ = c;
157                     if (c == '\n') {
158                               plinno++;
159                               break;
160                     }
161           }
162           *p = '\0';
163           return line;
164 }
165 #endif
166 
167 
168 /*
169  * Read a character from the script, returning PEOF on end of file.
170  * Nul characters in the input are silently discarded.
171  */
172 
173 int
pgetc(void)174 pgetc(void)
175 {
176           int c;
177 
178           c = pgetc_macro();
179           if (c == PFAKE)
180                     c = pgetc_macro();
181           return c;
182 }
183 
184 
185 static int
preadfd(void)186 preadfd(void)
187 {
188           int nr;
189           char *buf =  parsefile->buf;
190           parsenextc = buf;
191 
192  retry:
193 #ifndef SMALL
194           if (parsefile->fd == 0 && el) {
195                     static const char *rl_cp;
196                     static int el_len;
197 
198                     if (rl_cp == NULL)
199                               rl_cp = el_gets(el, &el_len);
200                     if (rl_cp == NULL)
201                               nr = el_len == 0 ? 0 : -1;
202                     else {
203                               nr = el_len;
204                               if (nr > BUFSIZ - 8)
205                                         nr = BUFSIZ - 8;
206                               memcpy(buf, rl_cp, nr);
207                               if (nr != el_len) {
208                                         el_len -= nr;
209                                         rl_cp += nr;
210                               } else
211                                         rl_cp = 0;
212                     }
213 
214           } else
215 #endif
216                     nr = read(parsefile->fd, buf, BUFSIZ - 8);
217 
218 
219           if (nr <= 0) {
220                     if (nr < 0) {
221                               if (errno == EINTR)
222                                         goto retry;
223                               if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
224                                         int flags = fcntl(0, F_GETFL, 0);
225 
226                                         if (flags >= 0 && flags & O_NONBLOCK) {
227                                                   flags &=~ O_NONBLOCK;
228                                                   if (fcntl(0, F_SETFL, flags) >= 0) {
229                                                             out2str("sh: turning off NDELAY mode\n");
230                                                             goto retry;
231                                                   }
232                                         }
233                               }
234                     }
235                     nr = -1;
236           }
237           return nr;
238 }
239 
240 /*
241  * Refill the input buffer and return the next input character:
242  *
243  * 1) If a string was pushed back on the input, pop it;
244  * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
245  *    from a string so we can't refill the buffer, return EOF.
246  * 3) If there is more stuff in this buffer, use it else call read to fill it.
247  * 4) Process input up to the next newline, deleting nul characters.
248  */
249 
250 int
preadbuffer(void)251 preadbuffer(void)
252 {
253           char *p, *q;
254           int more;
255 #ifndef SMALL
256           int something;
257 #endif
258           char savec;
259 
260           while (parsefile->strpush) {
261                     if (parsenleft == -1 && parsefile->strpush->ap != NULL)
262                               return PFAKE;
263                     popstring();
264                     if (--parsenleft >= 0)
265                               return (*parsenextc++);
266           }
267           if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
268                     return PEOF;
269           flushout(&output);
270           flushout(&errout);
271 
272  again:
273           if (parselleft <= 0) {
274                     if ((parselleft = preadfd()) == -1) {
275                               parselleft = parsenleft = EOF_NLEFT;
276                               return PEOF;
277                     }
278                     parsefile->nskip = 0;
279           }
280 
281                     /* jump over slots for any \0 chars that were dropped */
282           parsenextc += parsefile->nskip;
283           parsefile->nskip = 0;
284 
285                     /* p = (not const char *)parsenextc; */
286           p = parsefile->buf + (parsenextc - parsefile->buf);
287           q = p;
288 
289           /* delete nul characters */
290 #ifndef SMALL
291           something = 0;
292 #endif
293           for (more = 1; more;) {
294                     switch (*p) {
295                     case '\0':
296 #ifdef REJECT_NULS
297                               parsenleft = parselleft = 0;
298                               error("nul ('\\0') in shell input");
299                               /* NOTREACHED */
300 #else
301                               p++;      /* Skip nul */
302                               parsefile->nskip++;
303                               goto check;
304 #endif
305 
306                     case '\t':
307                     case ' ':
308                               break;
309 
310                     case '\n':
311                               parsenleft = q - parsenextc;
312                               more = 0; /* Stop processing here */
313                               break;
314 
315                     default:
316 #ifndef SMALL
317                               something = 1;
318 #endif
319                               break;
320                     }
321 
322                     if (parsefile->nskip)
323                               *q++ = *p++;
324                     else
325                               q = ++p;
326 
327 #ifndef REJECT_NULS
328  check:;
329 #endif
330                     if (--parselleft <= 0) {
331                               parsenleft = q - parsenextc - 1;
332                               if (parsenleft < 0)
333                                         goto again;
334                               *q = '\0';
335                               more = 0;
336                     }
337           }
338 
339           savec = *q;
340           *q = '\0';
341 
342 #ifndef SMALL
343           if (parsefile->fd == 0 && hist && (something || whichprompt == 2)) {
344                     HistEvent he;
345 
346                     INTOFF;
347                     history(hist, &he, whichprompt != 2 ? H_ENTER : H_APPEND,
348                         parsenextc);
349                     if (whichprompt != 2 && HistFP != NULL) {
350                               history(hist, &he, H_NSAVE_FP, (size_t)0, HistFP);
351                               fflush(HistFP);
352                     }
353                     INTON;
354           }
355 #endif
356 
357           if (vflag) {
358                     out2str(parsenextc);
359                     flushout(out2);
360           }
361 
362           *q = savec;
363 
364           return *parsenextc++;
365 }
366 
367 /*
368  * Test whether we have reached EOF on input stream.
369  * Return true only if certain (without attempting a read).
370  *
371  * Note the similarity to the opening section of preadbuffer()
372  */
373 int
at_eof(void)374 at_eof(void)
375 {
376           struct strpush *sp = parsefile->strpush;
377 
378           if (parsenleft > 0) /* more chars are in the buffer */
379                     return 0;
380 
381           while (sp != NULL) {
382                     /*
383                      * If any pushed string has any remaining data,
384                      * then we are not at EOF  (simulating popstring())
385                      */
386                     if (sp->prevnleft > 0)
387                               return 0;
388                     sp = sp->prev;
389           }
390 
391           /*
392            * If we reached real EOF and pushed it back,
393            * or if we are just processing a string (not reading a file)
394            * then there is no more.   Note that if a file pushes a
395            * string, the file's ->buf remains present.
396            */
397           if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
398                     return 1;
399 
400           /*
401            * In other cases, there might be more
402            */
403           return 0;
404 }
405 
406 /*
407  * Undo the last call to pgetc.  Only one character may be pushed back.
408  * PEOF may be pushed back.
409  */
410 
411 void
pungetc(void)412 pungetc(void)
413 {
414           parsenleft++;
415           parsenextc--;
416 }
417 
418 /*
419  * Push a string back onto the input at this current parsefile level.
420  * We handle aliases this way.
421  */
422 void
pushstring(const char * s,int len,struct alias * ap)423 pushstring(const char *s, int len, struct alias *ap)
424 {
425           struct strpush *sp;
426 
427           VTRACE(DBG_INPUT,
428               ("pushstring(\"%.*s\", %d)%s%s%s had: nl=%d ll=%d \"%.*s\"\n",
429               len, s, len, ap ? " for alias:'" : "",
430               ap ? ap->name : "", ap ? "'" : "",
431               parsenleft, parselleft, parsenleft, parsenextc));
432 
433           INTOFF;
434           if (parsefile->strpush) {
435                     sp = ckmalloc(sizeof (struct strpush));
436                     sp->prev = parsefile->strpush;
437                     parsefile->strpush = sp;
438           } else
439                     sp = parsefile->strpush = &(parsefile->basestrpush);
440 
441           sp->prevstring = parsenextc;
442           sp->prevnleft = parsenleft;
443           sp->prevlleft = parselleft;
444           sp->ap = ap;
445           if (ap)
446                     ap->flag |= ALIASINUSE;
447           parsenextc = s;
448           parsenleft = len;
449           INTON;
450 }
451 
452 void
popstring(void)453 popstring(void)
454 {
455           struct strpush *sp = parsefile->strpush;
456 
457           INTOFF;
458           if (sp->ap) {
459                     int alen;
460 
461                     if ((alen = strlen(sp->ap->val)) > 0 &&
462                         (sp->ap->val[alen - 1] == ' ' ||
463                          sp->ap->val[alen - 1] == '\t'))
464                               checkkwd |= CHKALIAS;
465                     sp->ap->flag &= ~ALIASINUSE;
466           }
467           parsenextc = sp->prevstring;
468           parsenleft = sp->prevnleft;
469           parselleft = sp->prevlleft;
470 
471           VTRACE(DBG_INPUT, ("popstring()%s%s%s nl=%d ll=%d \"%.*s\"\n",
472               sp->ap ? " from alias:'" : "", sp->ap ? sp->ap->name : "",
473               sp->ap ? "'" : "", parsenleft, parselleft, parsenleft, parsenextc));
474 
475           parsefile->strpush = sp->prev;
476           if (sp != &(parsefile->basestrpush))
477                     ckfree(sp);
478           INTON;
479 }
480 
481 /*
482  * Set the input to take input from a file.  If push is set, push the
483  * old input onto the stack first.
484  */
485 
486 void
setinputfile(const char * fname,int push)487 setinputfile(const char *fname, int push)
488 {
489           unsigned char magic[4];
490           int fd;
491           int fd2;
492           struct stat sb;
493 
494           CTRACE(DBG_INPUT,("setinputfile(\"%s\", %spush)\n",fname,push?"":"no"));
495 
496           INTOFF;
497           if ((fd = open(fname, O_RDONLY)) < 0)
498                     error("Can't open %s", fname);
499 
500           /* Since the message "Syntax error: "(" unexpected" is not very
501            * helpful, we check if the file starts with the ELF magic to
502            * avoid that message. The first lseek tries to make sure that
503            * we can later rewind the file.
504            */
505           if (fstat(fd, &sb) == 0 && S_ISREG(sb.st_mode) &&
506               lseek(fd, 0, SEEK_SET) == 0) {
507                     if (read(fd, magic, 4) == 4) {
508                               if (memcmp(magic, "\177ELF", 4) == 0) {
509                                         (void)close(fd);
510                                         error("Cannot execute ELF binary %s", fname);
511                               }
512                     }
513                     if (lseek(fd, 0, SEEK_SET) != 0) {
514                               (void)close(fd);
515                               error("Cannot rewind the file %s", fname);
516                     }
517           }
518 
519           fd2 = to_upper_fd(fd);        /* closes fd, returns higher equiv */
520           if (fd2 == fd) {
521                     (void) close(fd);
522                     error("Out of file descriptors");
523           }
524 
525           setinputfd(fd2, push);
526           INTON;
527 }
528 
529 /*
530  * When a shell fd needs to be altered (when the user wants to use
531  * the same fd - rare, but happens - we need to locate the ref to
532  * the fd, and update it.  This happens via a callback.
533  * This is the callback func for fd's used for shell input
534  */
535 static void
input_fd_swap(int from,int to)536 input_fd_swap(int from, int to)
537 {
538           struct parsefile *pf;
539 
540           pf = parsefile;
541           while (pf != NULL) {                    /* don't need to stop at basepf */
542                     if (pf->fd == from)
543                               pf->fd = to;
544                     pf = pf->prev;
545           }
546 }
547 
548 /*
549  * Like setinputfile, but takes an open file descriptor.  Call this with
550  * interrupts off.
551  */
552 
553 void
setinputfd(int fd,int push)554 setinputfd(int fd, int push)
555 {
556           VTRACE(DBG_INPUT, ("setinputfd(%d, %spush)\n", fd, push?"":"no"));
557 
558           INTOFF;
559           register_sh_fd(fd, input_fd_swap);
560           (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
561           if (push)
562                     pushfile();
563           if (parsefile->fd > 0)
564                     sh_close(parsefile->fd);
565           parsefile->fd = fd;
566           if (parsefile->buf == NULL)
567                     parsefile->buf = ckmalloc(BUFSIZ);
568           parselleft = parsenleft = 0;
569           plinno = 1;
570           INTON;
571 
572           CTRACE(DBG_INPUT, ("setinputfd(%d, %spush) done; plinno=1\n", fd,
573               push ? "" : "no"));
574 }
575 
576 
577 /*
578  * Like setinputfile, but takes input from a string.
579  */
580 
581 void
setinputstring(const char * string,int push,int line1)582 setinputstring(const char *string, int push, int line1)
583 {
584 
585           INTOFF;
586           if (push)           /* XXX: always, as it happens */
587                     pushfile();
588           parsenextc = string;
589           parselleft = parsenleft = strlen(string);
590           plinno = line1;
591           INTON;
592 
593           CTRACE(DBG_INPUT,
594               ("setinputstring(\"%.20s%s\" (%d), %spush, @ %d)\n", string,
595               (parsenleft > 20 ? "..." : ""), parsenleft, push?"":"no", line1));
596 }
597 
598 
599 
600 /*
601  * To handle the "." command, a stack of input files is used.  Pushfile
602  * adds a new entry to the stack and popfile restores the previous level.
603  */
604 
605 STATIC void
pushfile(void)606 pushfile(void)
607 {
608           struct parsefile *pf;
609 
610           VTRACE(DBG_INPUT,
611               ("pushfile(): fd=%d buf=%p nl=%d ll=%d \"%.*s\" plinno=%d\n",
612               parsefile->fd, parsefile->buf, parsenleft, parselleft,
613               parsenleft, parsenextc, plinno));
614 
615           parsefile->nleft = parsenleft;
616           parsefile->lleft = parselleft;
617           parsefile->nextc = parsenextc;
618           parsefile->linno = plinno;
619           pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
620           pf->prev = parsefile;
621           pf->fd = -1;
622           pf->strpush = NULL;
623           pf->basestrpush.prev = NULL;
624           pf->buf = NULL;
625           parsefile = pf;
626 }
627 
628 
629 void
popfile(void)630 popfile(void)
631 {
632           struct parsefile *pf = parsefile;
633 
634           INTOFF;
635           if (pf->fd >= 0)
636                     sh_close(pf->fd);
637           if (pf->buf)
638                     ckfree(pf->buf);
639           while (pf->strpush)
640                     popstring();
641           parsefile = pf->prev;
642           ckfree(pf);
643           parsenleft = parsefile->nleft;
644           parselleft = parsefile->lleft;
645           parsenextc = parsefile->nextc;
646 
647           VTRACE(DBG_INPUT,
648               ("popfile(): fd=%d buf=%p nl=%d ll=%d \"%.*s\" plinno:%d->%d\n",
649               parsefile->fd, parsefile->buf, parsenleft, parselleft,
650               parsenleft, parsenextc, plinno, parsefile->linno));
651 
652           plinno = parsefile->linno;
653           INTON;
654 }
655 
656 /*
657  * Return current file (to go back to it later using popfilesupto()).
658  */
659 
660 struct parsefile *
getcurrentfile(void)661 getcurrentfile(void)
662 {
663           return parsefile;
664 }
665 
666 
667 /*
668  * Pop files until the given file is on top again. Useful for regular
669  * builtins that read shell commands from files or strings.
670  * If the given file is not an active file, an error is raised.
671  */
672 
673 void
popfilesupto(struct parsefile * file)674 popfilesupto(struct parsefile *file)
675 {
676           while (parsefile != file && parsefile != &basepf)
677                     popfile();
678           if (parsefile != file)
679                     error("popfilesupto() misused");
680 }
681 
682 
683 /*
684  * Return to top level.
685  */
686 
687 void
popallfiles(void)688 popallfiles(void)
689 {
690           while (parsefile != &basepf)
691                     popfile();
692 }
693 
694 
695 
696 /*
697  * Close the file(s) that the shell is reading commands from.  Called
698  * after a fork is done.
699  *
700  * Takes one arg, vfork, which tells it to not modify its global vars
701  * as it is still running in the parent.
702  *
703  * This code is (probably) unnecessary as the 'close on exec' flag is
704  * set and should be enough.  In the vfork case it is definitely wrong
705  * to close the fds as another fork() may be done later to feed data
706  * from a 'here' document into a pipe and we don't want to close the
707  * pipe!
708  */
709 
710 void
closescript(int vforked)711 closescript(int vforked)
712 {
713           if (vforked)
714                     return;
715           popallfiles();
716           if (parsefile->fd > 0) {
717                     sh_close(parsefile->fd);
718                     parsefile->fd = 0;
719           }
720 }
721