421fcd97daea46a72e151aef8de9746d11fac94e
[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. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * @(#)input.c  8.3 (Berkeley) 6/9/95
33  * $FreeBSD: head/bin/sh/input.c 245676 2013-01-19 22:12:08Z jilles $
34  */
35
36 #include <stdio.h>      /* defines BUFSIZ */
37 #include <fcntl.h>
38 #include <errno.h>
39 #include <unistd.h>
40 #include <stdlib.h>
41 #include <string.h>
42
43 /*
44  * This file implements the input routines used by the parser.
45  */
46
47 #include "shell.h"
48 #include "redir.h"
49 #include "syntax.h"
50 #include "input.h"
51 #include "output.h"
52 #include "options.h"
53 #include "memalloc.h"
54 #include "error.h"
55 #include "alias.h"
56 #include "parser.h"
57 #include "myhistedit.h"
58 #include "trap.h"
59
60 #define EOF_NLEFT -99           /* value of parsenleft when EOF pushed back */
61
62 struct strpush {
63         struct strpush *prev;   /* preceding string on stack */
64         char *prevstring;
65         int prevnleft;
66         int prevlleft;
67         struct alias *ap;       /* if push was associated with an alias */
68 };
69
70 /*
71  * The parsefile structure pointed to by the global variable parsefile
72  * contains information about the current file being read.
73  */
74
75 struct parsefile {
76         struct parsefile *prev; /* preceding file on stack */
77         int linno;              /* current line */
78         int fd;                 /* file descriptor (or -1 if string) */
79         int nleft;              /* number of chars left in this line */
80         int lleft;              /* number of lines left in this buffer */
81         char *nextc;            /* next char in buffer */
82         char *buf;              /* input buffer */
83         struct strpush *strpush; /* for pushing strings at this level */
84         struct strpush basestrpush; /* so pushing one is fast */
85 };
86
87
88 int plinno = 1;                 /* input line number */
89 int parsenleft;                 /* copy of parsefile->nleft */
90 MKINIT int parselleft;          /* copy of parsefile->lleft */
91 char *parsenextc;               /* copy of parsefile->nextc */
92 static char basebuf[BUFSIZ + 1];/* buffer for top level input file */
93 static struct parsefile basepf = {      /* top level input file */
94         .nextc = basebuf,
95         .buf = basebuf
96 };
97 static struct parsefile *parsefile = &basepf;   /* current input file */
98 int whichprompt;                /* 1 == PS1, 2 == PS2 */
99
100 EditLine *el;                   /* cookie for editline package */
101
102 static void pushfile(void);
103 static int preadfd(void);
104 static void popstring(void);
105
106 #ifdef mkinit
107 INCLUDE <stdio.h>
108 INCLUDE "input.h"
109 INCLUDE "error.h"
110
111 RESET {
112         popallfiles();
113         parselleft = parsenleft = 0;    /* clear input buffer */
114 }
115 #endif
116
117
118 /*
119  * Read a line from the script.
120  */
121
122 char *
123 pfgets(char *line, int len)
124 {
125         char *p = line;
126         int nleft = len;
127         int c;
128
129         while (--nleft > 0) {
130                 c = pgetc_macro();
131                 if (c == PEOF) {
132                         if (p == line)
133                                 return NULL;
134                         break;
135                 }
136                 *p++ = c;
137                 if (c == '\n')
138                         break;
139         }
140         *p = '\0';
141         return line;
142 }
143
144
145
146 /*
147  * Read a character from the script, returning PEOF on end of file.
148  * Nul characters in the input are silently discarded.
149  */
150
151 int
152 pgetc(void)
153 {
154         return pgetc_macro();
155 }
156
157
158 static int
159 preadfd(void)
160 {
161         int nr;
162         parsenextc = parsefile->buf;
163
164 #ifndef NO_HISTORY
165         if (el != NULL && gotwinch) {
166                 gotwinch = 0;
167                 el_resize(el);
168         }
169 #endif
170 retry:
171 #ifndef NO_HISTORY
172         if (parsefile->fd == 0 && el) {
173                 static const char *rl_cp;
174                 static int el_len;
175
176                 if (rl_cp == NULL)
177                         rl_cp = el_gets(el, &el_len);
178                 if (rl_cp == NULL)
179                         nr = el_len == 0 ? 0 : -1;
180                 else {
181                         nr = el_len;
182                         if (nr > BUFSIZ)
183                                 nr = BUFSIZ;
184                         memcpy(parsenextc, rl_cp, nr);
185                         if (nr != el_len) {
186                                 el_len -= nr;
187                                 rl_cp += nr;
188                         } else
189                                 rl_cp = NULL;
190                 }
191         } else
192 #endif
193                 nr = read(parsefile->fd, parsenextc, BUFSIZ);
194
195         if (nr <= 0) {
196                 if (nr < 0) {
197                         if (errno == EINTR)
198                                 goto retry;
199                         if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
200                                 int flags = fcntl(0, F_GETFL, 0);
201                                 if (flags >= 0 && flags & O_NONBLOCK) {
202                                         flags &=~ O_NONBLOCK;
203                                         if (fcntl(0, F_SETFL, flags) >= 0) {
204                                                 out2fmt_flush("sh: turning off NDELAY mode\n");
205                                                 goto retry;
206                                         }
207                                 }
208                         }
209                 }
210                 nr = -1;
211         }
212         return nr;
213 }
214
215 /*
216  * Refill the input buffer and return the next input character:
217  *
218  * 1) If a string was pushed back on the input, pop it;
219  * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
220  *    from a string so we can't refill the buffer, return EOF.
221  * 3) If there is more in this buffer, use it else call read to fill it.
222  * 4) Process input up to the next newline, deleting nul characters.
223  */
224
225 int
226 preadbuffer(void)
227 {
228         char *p, *q;
229         int more;
230         int something;
231         char savec;
232
233         if (parsefile->strpush) {
234                 popstring();
235                 if (--parsenleft >= 0)
236                         return (*parsenextc++);
237         }
238         if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
239                 return PEOF;
240         flushout(&output);
241         flushout(&errout);
242
243 again:
244         if (parselleft <= 0) {
245                 if ((parselleft = preadfd()) == -1) {
246                         parselleft = parsenleft = EOF_NLEFT;
247                         return PEOF;
248                 }
249         }
250
251         q = p = parsenextc;
252
253         /* delete nul characters */
254         something = 0;
255         for (more = 1; more;) {
256                 switch (*p) {
257                 case '\0':
258                         p++;    /* Skip nul */
259                         goto check;
260
261                 case '\t':
262                 case ' ':
263                         break;
264
265                 case '\n':
266                         parsenleft = q - parsenextc;
267                         more = 0; /* Stop processing here */
268                         break;
269
270                 default:
271                         something = 1;
272                         break;
273                 }
274
275                 *q++ = *p++;
276 check:
277                 if (--parselleft <= 0) {
278                         parsenleft = q - parsenextc - 1;
279                         if (parsenleft < 0)
280                                 goto again;
281                         *q = '\0';
282                         more = 0;
283                 }
284         }
285
286         savec = *q;
287         *q = '\0';
288
289 #ifndef NO_HISTORY
290         if (parsefile->fd == 0 && hist && something) {
291                 HistEvent he;
292                 INTOFF;
293                 history(hist, &he, whichprompt == 1 ? H_ENTER : H_ADD,
294                     parsenextc);
295                 INTON;
296         }
297 #endif
298
299         if (vflag) {
300                 out2str(parsenextc);
301                 flushout(out2);
302         }
303
304         *q = savec;
305
306         return *parsenextc++;
307 }
308
309 /*
310  * Returns if we are certain we are at EOF. Does not cause any more input
311  * to be read from the outside world.
312  */
313
314 int
315 preadateof(void)
316 {
317         if (parsenleft > 0)
318                 return 0;
319         if (parsefile->strpush)
320                 return 0;
321         if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
322                 return 1;
323         return 0;
324 }
325
326 /*
327  * Undo the last call to pgetc.  Only one character may be pushed back.
328  * PEOF may be pushed back.
329  */
330
331 void
332 pungetc(void)
333 {
334         parsenleft++;
335         parsenextc--;
336 }
337
338 /*
339  * Push a string back onto the input at this current parsefile level.
340  * We handle aliases this way.
341  */
342 void
343 pushstring(char *s, int len, struct alias *ap)
344 {
345         struct strpush *sp;
346
347         INTOFF;
348 /*out2fmt_flush("*** calling pushstring: %s, %d\n", s, len);*/
349         if (parsefile->strpush) {
350                 sp = ckmalloc(sizeof (struct strpush));
351                 sp->prev = parsefile->strpush;
352                 parsefile->strpush = sp;
353         } else
354                 sp = parsefile->strpush = &(parsefile->basestrpush);
355         sp->prevstring = parsenextc;
356         sp->prevnleft = parsenleft;
357         sp->prevlleft = parselleft;
358         sp->ap = ap;
359         if (ap)
360                 ap->flag |= ALIASINUSE;
361         parsenextc = s;
362         parsenleft = len;
363         INTON;
364 }
365
366 static void
367 popstring(void)
368 {
369         struct strpush *sp = parsefile->strpush;
370
371         INTOFF;
372         parsenextc = sp->prevstring;
373         parsenleft = sp->prevnleft;
374         parselleft = sp->prevlleft;
375 /*out2fmt_flush("*** calling popstring: restoring to '%s'\n", parsenextc);*/
376         if (sp->ap)
377                 sp->ap->flag &= ~ALIASINUSE;
378         parsefile->strpush = sp->prev;
379         if (sp != &(parsefile->basestrpush))
380                 ckfree(sp);
381         INTON;
382 }
383
384 /*
385  * Set the input to take input from a file.  If push is set, push the
386  * old input onto the stack first.
387  */
388
389 void
390 setinputfile(const char *fname, int push)
391 {
392         int fd;
393         int fd2;
394
395         INTOFF;
396         if ((fd = open(fname, O_RDONLY)) < 0)
397                 error("cannot open %s: %s", fname, strerror(errno));
398         if (fd < 10) {
399                 fd2 = fcntl(fd, F_DUPFD, 10);
400                 close(fd);
401                 if (fd2 < 0)
402                         error("Out of file descriptors");
403                 fd = fd2;
404         }
405         setinputfd(fd, push);
406         INTON;
407 }
408
409
410 /*
411  * Like setinputfile, but takes an open file descriptor.  Call this with
412  * interrupts off.
413  */
414
415 void
416 setinputfd(int fd, int push)
417 {
418         fcntl(fd, F_SETFD, FD_CLOEXEC);
419         if (push) {
420                 pushfile();
421                 parsefile->buf = ckmalloc(BUFSIZ + 1);
422         }
423         if (parsefile->fd > 0)
424                 close(parsefile->fd);
425         parsefile->fd = fd;
426         if (parsefile->buf == NULL)
427                 parsefile->buf = ckmalloc(BUFSIZ + 1);
428         parselleft = parsenleft = 0;
429         plinno = 1;
430 }
431
432
433 /*
434  * Like setinputfile, but takes input from a string.
435  */
436
437 void
438 setinputstring(char *string, int push)
439 {
440         INTOFF;
441         if (push)
442                 pushfile();
443         parsenextc = string;
444         parselleft = parsenleft = strlen(string);
445         parsefile->buf = NULL;
446         plinno = 1;
447         INTON;
448 }
449
450
451
452 /*
453  * To handle the "." command, a stack of input files is used.  Pushfile
454  * adds a new entry to the stack and popfile restores the previous level.
455  */
456
457 static void
458 pushfile(void)
459 {
460         struct parsefile *pf;
461
462         parsefile->nleft = parsenleft;
463         parsefile->lleft = parselleft;
464         parsefile->nextc = parsenextc;
465         parsefile->linno = plinno;
466         pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
467         pf->prev = parsefile;
468         pf->fd = -1;
469         pf->strpush = NULL;
470         pf->basestrpush.prev = NULL;
471         parsefile = pf;
472 }
473
474
475 void
476 popfile(void)
477 {
478         struct parsefile *pf = parsefile;
479
480         INTOFF;
481         if (pf->fd >= 0)
482                 close(pf->fd);
483         if (pf->buf)
484                 ckfree(pf->buf);
485         while (pf->strpush)
486                 popstring();
487         parsefile = pf->prev;
488         ckfree(pf);
489         parsenleft = parsefile->nleft;
490         parselleft = parsefile->lleft;
491         parsenextc = parsefile->nextc;
492         plinno = parsefile->linno;
493         INTON;
494 }
495
496
497 /*
498  * Return current file (to go back to it later using popfilesupto()).
499  */
500
501 struct parsefile *
502 getcurrentfile(void)
503 {
504         return parsefile;
505 }
506
507
508 /*
509  * Pop files until the given file is on top again. Useful for regular
510  * builtins that read shell commands from files or strings.
511  * If the given file is not an active file, an error is raised.
512  */
513
514 void
515 popfilesupto(struct parsefile *file)
516 {
517         while (parsefile != file && parsefile != &basepf)
518                 popfile();
519         if (parsefile != file)
520                 error("popfilesupto() misused");
521 }
522
523 /*
524  * Return to top level.
525  */
526
527 void
528 popallfiles(void)
529 {
530         while (parsefile != &basepf)
531                 popfile();
532 }
533
534
535
536 /*
537  * Close the file(s) that the shell is reading commands from.  Called
538  * after a fork is done.
539  */
540
541 void
542 closescript(void)
543 {
544         popallfiles();
545         if (parsefile->fd > 0) {
546                 close(parsefile->fd);
547                 parsefile->fd = 0;
548         }
549 }