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