xref: /netbsd-src/bin/csh/func.c (revision 0bf6fd0c5977c19d17d479b5e122bcf77ed31a09)
1 /*	$NetBSD: func.c,v 1.18 2000/05/31 22:48:45 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1980, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #ifndef lint
38 #if 0
39 static char sccsid[] = "@(#)func.c	8.1 (Berkeley) 5/31/93";
40 #else
41 __RCSID("$NetBSD: func.c,v 1.18 2000/05/31 22:48:45 christos Exp $");
42 #endif
43 #endif /* not lint */
44 
45 #include <sys/types.h>
46 #include <sys/stat.h>
47 #include <signal.h>
48 #include <locale.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52 #if __STDC__
53 # include <stdarg.h>
54 #else
55 # include <varargs.h>
56 #endif
57 
58 #include "csh.h"
59 #include "extern.h"
60 #include "pathnames.h"
61 
62 extern char **environ;
63 
64 static void	islogin __P((void));
65 static void	reexecute __P((struct command *));
66 static void	preread __P((void));
67 static void	doagain __P((void));
68 static void	search __P((int, int, Char *));
69 static int	getword __P((Char *));
70 static int	keyword __P((Char *));
71 static void	toend __P((void));
72 static void	xecho __P((int, Char **));
73 static void	Unsetenv __P((Char *));
74 
75 struct biltins *
76 isbfunc(t)
77     struct command *t;
78 {
79     Char *cp = t->t_dcom[0];
80     struct biltins *bp, *bp1, *bp2;
81     static struct biltins label = {"", dozip, 0, 0};
82     static struct biltins foregnd = {"%job", dofg1, 0, 0};
83     static struct biltins backgnd = {"%job &", dobg1, 0, 0};
84 
85     if (lastchr(cp) == ':') {
86 	label.bname = short2str(cp);
87 	return (&label);
88     }
89     if (*cp == '%') {
90 	if (t->t_dflg & F_AMPERSAND) {
91 	    t->t_dflg &= ~F_AMPERSAND;
92 	    backgnd.bname = short2str(cp);
93 	    return (&backgnd);
94 	}
95 	foregnd.bname = short2str(cp);
96 	return (&foregnd);
97     }
98     /*
99      * Binary search Bp1 is the beginning of the current search range. Bp2 is
100      * one past the end.
101      */
102     for (bp1 = bfunc, bp2 = bfunc + nbfunc; bp1 < bp2;) {
103 	int i;
104 
105 	bp = bp1 + ((bp2 - bp1) >> 1);
106 	if ((i = *cp - *bp->bname) == 0 &&
107 	    (i = Strcmp(cp, str2short(bp->bname))) == 0)
108 	    return bp;
109 	if (i < 0)
110 	    bp2 = bp;
111 	else
112 	    bp1 = bp + 1;
113     }
114     return (0);
115 }
116 
117 void
118 func(t, bp)
119     struct command *t;
120     struct biltins *bp;
121 {
122     int     i;
123 
124     xechoit(t->t_dcom);
125     setname(bp->bname);
126     i = blklen(t->t_dcom) - 1;
127     if (i < bp->minargs)
128 	stderror(ERR_NAME | ERR_TOOFEW);
129     if (i > bp->maxargs)
130 	stderror(ERR_NAME | ERR_TOOMANY);
131     (*bp->bfunct) (t->t_dcom, t);
132 }
133 
134 void
135 /*ARGSUSED*/
136 doonintr(v, t)
137     Char **v;
138     struct command *t;
139 {
140     Char *cp;
141     Char *vv = v[1];
142     sigset_t sigset;
143 
144     if (parintr == SIG_IGN)
145 	return;
146     if (setintr && intty)
147 	stderror(ERR_NAME | ERR_TERMINAL);
148     cp = gointr;
149     gointr = 0;
150     xfree((ptr_t) cp);
151     if (vv == 0) {
152 	if (setintr) {
153 	    sigemptyset(&sigset);
154 	    (void) sigaddset(&sigset, SIGINT);
155 	    (void) sigprocmask(SIG_BLOCK, &sigset, NULL);
156 	} else
157 	    (void) signal(SIGINT, SIG_DFL);
158 	gointr = 0;
159     }
160     else if (eq((vv = strip(vv)), STRminus)) {
161 	(void) signal(SIGINT, SIG_IGN);
162 	gointr = Strsave(STRminus);
163     }
164     else {
165 	gointr = Strsave(vv);
166 	(void) signal(SIGINT, pintr);
167     }
168 }
169 
170 void
171 /*ARGSUSED*/
172 donohup(v, t)
173     Char **v;
174     struct command *t;
175 {
176     if (intty)
177 	stderror(ERR_NAME | ERR_TERMINAL);
178     if (setintr == 0) {
179 	(void) signal(SIGHUP, SIG_IGN);
180     }
181 }
182 
183 void
184 /*ARGSUSED*/
185 dozip(v, t)
186     Char **v;
187     struct command *t;
188 {
189     ;
190 }
191 
192 void
193 prvars()
194 {
195     plist(&shvhed);
196 }
197 
198 void
199 /*ARGSUSED*/
200 doalias(v, t)
201     Char **v;
202     struct command *t;
203 {
204     struct varent *vp;
205     Char *p;
206 
207     v++;
208     p = *v++;
209     if (p == 0)
210 	plist(&aliases);
211     else if (*v == 0) {
212 	vp = adrof1(strip(p), &aliases);
213 	if (vp) {
214 	    blkpr(cshout, vp->vec);
215 	    (void) fputc('\n', cshout);
216 	}
217     }
218     else {
219 	if (eq(p, STRalias) || eq(p, STRunalias)) {
220 	    setname(vis_str(p));
221 	    stderror(ERR_NAME | ERR_DANGER);
222 	}
223 	set1(strip(p), saveblk(v), &aliases);
224     }
225 }
226 
227 void
228 /*ARGSUSED*/
229 unalias(v, t)
230     Char **v;
231     struct command *t;
232 {
233     unset1(v, &aliases);
234 }
235 
236 void
237 /*ARGSUSED*/
238 dologout(v, t)
239     Char **v;
240     struct command *t;
241 {
242     islogin();
243     goodbye();
244 }
245 
246 void
247 /*ARGSUSED*/
248 dologin(v, t)
249     Char **v;
250     struct command *t;
251 {
252     islogin();
253     rechist();
254     (void) signal(SIGTERM, parterm);
255     (void) execl(_PATH_LOGIN, "login", short2str(v[1]), NULL);
256     untty();
257     xexit(1);
258     /* NOTREACHED */
259 }
260 
261 static void
262 islogin()
263 {
264     if (chkstop == 0 && setintr)
265 	panystop(0);
266     if (loginsh)
267 	return;
268     stderror(ERR_NOTLOGIN);
269     /* NOTREACHED */
270 }
271 
272 void
273 doif(v, kp)
274     Char  **v;
275     struct command *kp;
276 {
277     int i;
278     Char **vv;
279 
280     v++;
281     i = expr(&v);
282     vv = v;
283     if (*vv == NULL)
284 	stderror(ERR_NAME | ERR_EMPTYIF);
285     if (eq(*vv, STRthen)) {
286 	if (*++vv)
287 	    stderror(ERR_NAME | ERR_IMPRTHEN);
288 	setname(vis_str(STRthen));
289 	/*
290 	 * If expression was zero, then scan to else, otherwise just fall into
291 	 * following code.
292 	 */
293 	if (!i)
294 	    search(T_IF, 0, NULL);
295 	return;
296     }
297     /*
298      * Simple command attached to this if. Left shift the node in this tree,
299      * munging it so we can reexecute it.
300      */
301     if (i) {
302 	lshift(kp->t_dcom, vv - kp->t_dcom);
303 	reexecute(kp);
304 	donefds();
305     }
306 }
307 
308 /*
309  * Reexecute a command, being careful not
310  * to redo i/o redirection, which is already set up.
311  */
312 static void
313 reexecute(kp)
314     struct command *kp;
315 {
316     kp->t_dflg &= F_SAVE;
317     kp->t_dflg |= F_REPEAT;
318     /*
319      * If tty is still ours to arbitrate, arbitrate it; otherwise dont even set
320      * pgrp's as the jobs would then have no way to get the tty (we can't give
321      * it to them, and our parent wouldn't know their pgrp, etc.
322      */
323     execute(kp, (tpgrp > 0 ? tpgrp : -1), NULL, NULL);
324 }
325 
326 void
327 /*ARGSUSED*/
328 doelse(v, t)
329     Char **v;
330     struct command *t;
331 {
332     search(T_ELSE, 0, NULL);
333 }
334 
335 void
336 /*ARGSUSED*/
337 dogoto(v, t)
338     Char **v;
339     struct command *t;
340 {
341     Char   *lp;
342 
343     gotolab(lp = globone(v[1], G_ERROR));
344     xfree((ptr_t) lp);
345 }
346 
347 void
348 gotolab(lab)
349     Char *lab;
350 {
351     struct whyle *wp;
352     /*
353      * While we still can, locate any unknown ends of existing loops. This
354      * obscure code is the WORST result of the fact that we don't really parse.
355      */
356     for (wp = whyles; wp; wp = wp->w_next)
357 	if (wp->w_end.type == F_SEEK && wp->w_end.f_seek == 0) {
358 	    search(T_BREAK, 0, NULL);
359 	    btell(&wp->w_end);
360 	}
361 	else
362 	    bseek(&wp->w_end);
363     search(T_GOTO, 0, lab);
364     /*
365      * Eliminate loops which were exited.
366      */
367     wfree();
368 }
369 
370 void
371 /*ARGSUSED*/
372 doswitch(v, t)
373     Char **v;
374     struct command *t;
375 {
376     Char *cp, *lp;
377 
378     v++;
379     if (!*v || *(*v++) != '(')
380 	stderror(ERR_SYNTAX);
381     cp = **v == ')' ? STRNULL : *v++;
382     if (*(*v++) != ')')
383 	v--;
384     if (*v)
385 	stderror(ERR_SYNTAX);
386     search(T_SWITCH, 0, lp = globone(cp, G_ERROR));
387     xfree((ptr_t) lp);
388 }
389 
390 void
391 /*ARGSUSED*/
392 dobreak(v, t)
393     Char **v;
394     struct command *t;
395 {
396     if (whyles)
397 	toend();
398     else
399 	stderror(ERR_NAME | ERR_NOTWHILE);
400 }
401 
402 void
403 /*ARGSUSED*/
404 doexit(v, t)
405     Char **v;
406     struct command *t;
407 {
408     if (chkstop == 0 && (intty || intact) && evalvec == 0)
409 	panystop(0);
410     /*
411      * Don't DEMAND parentheses here either.
412      */
413     v++;
414     if (*v) {
415 	set(STRstatus, putn(expr(&v)));
416 	if (*v)
417 	    stderror(ERR_NAME | ERR_EXPRESSION);
418     }
419     btoeof();
420     if (intty)
421 	(void) close(SHIN);
422 }
423 
424 void
425 /*ARGSUSED*/
426 doforeach(v, t)
427     Char **v;
428     struct command *t;
429 {
430     Char *cp, *sp;
431     struct whyle *nwp;
432 
433     v++;
434     sp = cp = strip(*v);
435     if (!letter(*sp))
436 	stderror(ERR_NAME | ERR_VARBEGIN);
437     while (*cp && alnum(*cp))
438 	cp++;
439     if (*cp)
440 	stderror(ERR_NAME | ERR_VARALNUM);
441     if ((cp - sp) > MAXVARLEN)
442 	stderror(ERR_NAME | ERR_VARTOOLONG);
443     cp = *v++;
444     if (v[0][0] != '(' || v[blklen(v) - 1][0] != ')')
445 	stderror(ERR_NAME | ERR_NOPAREN);
446     v++;
447     gflag = 0, tglob(v);
448     v = globall(v);
449     if (v == 0)
450 	stderror(ERR_NAME | ERR_NOMATCH);
451     nwp = (struct whyle *) xcalloc(1, sizeof *nwp);
452     nwp->w_fe = nwp->w_fe0 = v;
453     gargv = 0;
454     btell(&nwp->w_start);
455     nwp->w_fename = Strsave(cp);
456     nwp->w_next = whyles;
457     nwp->w_end.type = F_SEEK;
458     whyles = nwp;
459     /*
460      * Pre-read the loop so as to be more comprehensible to a terminal user.
461      */
462     if (intty)
463 	preread();
464     doagain();
465 }
466 
467 void
468 /*ARGSUSED*/
469 dowhile(v, t)
470     Char **v;
471     struct command *t;
472 {
473     int status;
474     bool again = whyles != 0 && SEEKEQ(&whyles->w_start, &lineloc) &&
475     whyles->w_fename == 0;
476 
477     v++;
478     /*
479      * Implement prereading here also, taking care not to evaluate the
480      * expression before the loop has been read up from a terminal.
481      */
482     if (intty && !again)
483 	status = !exp0(&v, 1);
484     else
485 	status = !expr(&v);
486     if (*v)
487 	stderror(ERR_NAME | ERR_EXPRESSION);
488     if (!again) {
489 	struct whyle *nwp =
490 	(struct whyle *) xcalloc(1, sizeof(*nwp));
491 
492 	nwp->w_start = lineloc;
493 	nwp->w_end.type = F_SEEK;
494 	nwp->w_end.f_seek = 0;
495 	nwp->w_next = whyles;
496 	whyles = nwp;
497 	if (intty) {
498 	    /*
499 	     * The tty preread
500 	     */
501 	    preread();
502 	    doagain();
503 	    return;
504 	}
505     }
506     if (status)
507 	/* We ain't gonna loop no more, no more! */
508 	toend();
509 }
510 
511 static void
512 preread()
513 {
514     sigset_t sigset;
515 
516     whyles->w_end.type = I_SEEK;
517     if (setintr) {
518 	sigemptyset(&sigset);
519 	(void) sigaddset(&sigset, SIGINT);
520 	(void) sigprocmask(SIG_UNBLOCK, &sigset, NULL);
521     }
522 
523     search(T_BREAK, 0, NULL);		/* read the expression in */
524     if (setintr)
525 	(void) sigprocmask(SIG_BLOCK, &sigset, NULL);
526     btell(&whyles->w_end);
527 }
528 
529 void
530 /*ARGSUSED*/
531 doend(v, t)
532     Char **v;
533     struct command *t;
534 {
535     if (!whyles)
536 	stderror(ERR_NAME | ERR_NOTWHILE);
537     btell(&whyles->w_end);
538     doagain();
539 }
540 
541 void
542 /*ARGSUSED*/
543 docontin(v, t)
544     Char **v;
545     struct command *t;
546 {
547     if (!whyles)
548 	stderror(ERR_NAME | ERR_NOTWHILE);
549     doagain();
550 }
551 
552 static void
553 doagain()
554 {
555     /* Repeating a while is simple */
556     if (whyles->w_fename == 0) {
557 	bseek(&whyles->w_start);
558 	return;
559     }
560     /*
561      * The foreach variable list actually has a spurious word ")" at the end of
562      * the w_fe list.  Thus we are at the of the list if one word beyond this
563      * is 0.
564      */
565     if (!whyles->w_fe[1]) {
566 	dobreak(NULL, NULL);
567 	return;
568     }
569     set(whyles->w_fename, Strsave(*whyles->w_fe++));
570     bseek(&whyles->w_start);
571 }
572 
573 void
574 dorepeat(v, kp)
575     Char  **v;
576     struct command *kp;
577 {
578     int i;
579     sigset_t sigset;
580 
581     i = getn(v[1]);
582     if (setintr) {
583 	sigemptyset(&sigset);
584 	(void) sigaddset(&sigset, SIGINT);
585 	(void) sigprocmask(SIG_BLOCK, &sigset, NULL);
586     }
587     lshift(v, 2);
588     while (i > 0) {
589 	if (setintr)
590 	    (void) sigprocmask(SIG_UNBLOCK, &sigset, NULL);
591 	reexecute(kp);
592 	--i;
593     }
594     donefds();
595     if (setintr)
596 	(void) sigprocmask(SIG_UNBLOCK, &sigset, NULL);
597 }
598 
599 void
600 /*ARGSUSED*/
601 doswbrk(v, t)
602     Char **v;
603     struct command *t;
604 {
605     search(T_BRKSW, 0, NULL);
606 }
607 
608 int
609 srchx(cp)
610     Char *cp;
611 {
612     struct srch *sp, *sp1, *sp2;
613     int i;
614 
615     /*
616      * Binary search Sp1 is the beginning of the current search range. Sp2 is
617      * one past the end.
618      */
619     for (sp1 = srchn, sp2 = srchn + nsrchn; sp1 < sp2;) {
620 	sp = sp1 + ((sp2 - sp1) >> 1);
621 	if ((i = *cp - *sp->s_name) == 0 &&
622 	    (i = Strcmp(cp, str2short(sp->s_name))) == 0)
623 	    return sp->s_value;
624 	if (i < 0)
625 	    sp2 = sp;
626 	else
627 	    sp1 = sp + 1;
628     }
629     return (-1);
630 }
631 
632 static Char Stype;
633 static Char *Sgoal;
634 
635 /*VARARGS2*/
636 static void
637 search(type, level, goal)
638     int     type;
639     int level;
640     Char   *goal;
641 {
642     Char    wordbuf[BUFSIZE];
643     Char *aword = wordbuf;
644     Char *cp;
645 
646     Stype = type;
647     Sgoal = goal;
648     if (type == T_GOTO) {
649 	struct Ain a;
650 	a.type = F_SEEK;
651 	a.f_seek = 0;
652 	bseek(&a);
653     }
654     do {
655 	if (intty && fseekp == feobp && aret == F_SEEK)
656 	    (void) fprintf(cshout, "? "), (void) fflush(cshout);
657 	aword[0] = 0;
658 	(void) getword(aword);
659 	switch (srchx(aword)) {
660 
661 	case T_ELSE:
662 	    if (level == 0 && type == T_IF)
663 		return;
664 	    break;
665 
666 	case T_IF:
667 	    while (getword(aword))
668 		continue;
669 	    if ((type == T_IF || type == T_ELSE) &&
670 		eq(aword, STRthen))
671 		level++;
672 	    break;
673 
674 	case T_ENDIF:
675 	    if (type == T_IF || type == T_ELSE)
676 		level--;
677 	    break;
678 
679 	case T_FOREACH:
680 	case T_WHILE:
681 	    if (type == T_BREAK)
682 		level++;
683 	    break;
684 
685 	case T_END:
686 	    if (type == T_BREAK)
687 		level--;
688 	    break;
689 
690 	case T_SWITCH:
691 	    if (type == T_SWITCH || type == T_BRKSW)
692 		level++;
693 	    break;
694 
695 	case T_ENDSW:
696 	    if (type == T_SWITCH || type == T_BRKSW)
697 		level--;
698 	    break;
699 
700 	case T_LABEL:
701 	    if (type == T_GOTO && getword(aword) && eq(aword, goal))
702 		level = -1;
703 	    break;
704 
705 	default:
706 	    if (type != T_GOTO && (type != T_SWITCH || level != 0))
707 		break;
708 	    if (lastchr(aword) != ':')
709 		break;
710 	    aword[Strlen(aword) - 1] = 0;
711 	    if ((type == T_GOTO && eq(aword, goal)) ||
712 		(type == T_SWITCH && eq(aword, STRdefault)))
713 		level = -1;
714 	    break;
715 
716 	case T_CASE:
717 	    if (type != T_SWITCH || level != 0)
718 		break;
719 	    (void) getword(aword);
720 	    if (lastchr(aword) == ':')
721 		aword[Strlen(aword) - 1] = 0;
722 	    cp = strip(Dfix1(aword));
723 	    if (Gmatch(goal, cp))
724 		level = -1;
725 	    xfree((ptr_t) cp);
726 	    break;
727 
728 	case T_DEFAULT:
729 	    if (type == T_SWITCH && level == 0)
730 		level = -1;
731 	    break;
732 	}
733 	(void) getword(NULL);
734     } while (level >= 0);
735 }
736 
737 static int
738 getword(wp)
739     Char *wp;
740 {
741     int found = 0;
742     int c, d;
743     int     kwd = 0;
744     Char   *owp = wp;
745 
746     c = readc(1);
747     d = 0;
748     do {
749 	while (c == ' ' || c == '\t')
750 	    c = readc(1);
751 	if (c == '#')
752 	    do
753 		c = readc(1);
754 	    while (c >= 0 && c != '\n');
755 	if (c < 0)
756 	    goto past;
757 	if (c == '\n') {
758 	    if (wp)
759 		break;
760 	    return (0);
761 	}
762 	unreadc(c);
763 	found = 1;
764 	do {
765 	    c = readc(1);
766 	    if (c == '\\' && (c = readc(1)) == '\n')
767 		c = ' ';
768 	    if (c == '\'' || c == '"') {
769 		if (d == 0)
770 		    d = c;
771 		else if (d == c)
772 		    d = 0;
773 	    }
774 	    if (c < 0)
775 		goto past;
776 	    if (wp) {
777 		*wp++ = c;
778 		*wp = 0;	/* end the string b4 test */
779 	    }
780 	} while ((d || (!(kwd = keyword(owp)) && c != ' '
781 		  && c != '\t')) && c != '\n');
782     } while (wp == 0);
783 
784     /*
785      * if we have read a keyword ( "if", "switch" or "while" ) then we do not
786      * need to unreadc the look-ahead char
787      */
788     if (!kwd) {
789 	unreadc(c);
790 	if (found)
791 	    *--wp = 0;
792     }
793 
794     return (found);
795 
796 past:
797     switch (Stype) {
798 
799     case T_IF:
800 	stderror(ERR_NAME | ERR_NOTFOUND, "then/endif");
801 	/* NOTREACHED */
802 
803     case T_ELSE:
804 	stderror(ERR_NAME | ERR_NOTFOUND, "endif");
805 	/* NOTREACHED */
806 
807     case T_BRKSW:
808     case T_SWITCH:
809 	stderror(ERR_NAME | ERR_NOTFOUND, "endsw");
810 	/* NOTREACHED */
811 
812     case T_BREAK:
813 	stderror(ERR_NAME | ERR_NOTFOUND, "end");
814 	/* NOTREACHED */
815 
816     case T_GOTO:
817 	setname(vis_str(Sgoal));
818 	stderror(ERR_NAME | ERR_NOTFOUND, "label");
819 	/* NOTREACHED */
820     }
821     return (0);
822 }
823 
824 /*
825  * keyword(wp) determines if wp is one of the built-n functions if,
826  * switch or while. It seems that when an if statement looks like
827  * "if(" then getword above sucks in the '(' and so the search routine
828  * never finds what it is scanning for. Rather than rewrite doword, I hack
829  * in a test to see if the string forms a keyword. Then doword stops
830  * and returns the word "if" -strike
831  */
832 
833 static int
834 keyword(wp)
835     Char   *wp;
836 {
837     static Char STRif[] = {'i', 'f', '\0'};
838     static Char STRwhile[] = {'w', 'h', 'i', 'l', 'e', '\0'};
839     static Char STRswitch[] = {'s', 'w', 'i', 't', 'c', 'h', '\0'};
840 
841     if (!wp)
842 	return (0);
843 
844     if ((Strcmp(wp, STRif) == 0) || (Strcmp(wp, STRwhile) == 0)
845 	|| (Strcmp(wp, STRswitch) == 0))
846 	return (1);
847 
848     return (0);
849 }
850 
851 static void
852 toend()
853 {
854     if (whyles->w_end.type == F_SEEK && whyles->w_end.f_seek == 0) {
855 	search(T_BREAK, 0, NULL);
856 	btell(&whyles->w_end);
857 	whyles->w_end.f_seek--;
858     }
859     else
860 	bseek(&whyles->w_end);
861     wfree();
862 }
863 
864 void
865 wfree()
866 {
867     struct Ain    o;
868     struct whyle *nwp;
869 
870     btell(&o);
871 
872     for (; whyles; whyles = nwp) {
873 	struct whyle *wp = whyles;
874 	nwp = wp->w_next;
875 
876 	/*
877 	 * We free loops that have different seek types.
878 	 */
879 	if (wp->w_end.type != I_SEEK && wp->w_start.type == wp->w_end.type &&
880 	    wp->w_start.type == o.type) {
881 	    if (wp->w_end.type == F_SEEK) {
882 		if (o.f_seek >= wp->w_start.f_seek &&
883 		    (wp->w_end.f_seek == 0 || o.f_seek < wp->w_end.f_seek))
884 		    break;
885 	    }
886 	    else {
887 		if (o.a_seek >= wp->w_start.a_seek &&
888 		    (wp->w_end.a_seek == 0 || o.a_seek < wp->w_end.a_seek))
889 		    break;
890 	    }
891 	}
892 
893 	if (wp->w_fe0)
894 	    blkfree(wp->w_fe0);
895 	if (wp->w_fename)
896 	    xfree((ptr_t) wp->w_fename);
897 	xfree((ptr_t) wp);
898     }
899 }
900 
901 void
902 /*ARGSUSED*/
903 doecho(v, t)
904     Char **v;
905     struct command *t;
906 {
907     xecho(' ', v);
908 }
909 
910 void
911 /*ARGSUSED*/
912 doglob(v, t)
913     Char **v;
914     struct command *t;
915 {
916     xecho(0, v);
917     (void) fflush(cshout);
918 }
919 
920 static void
921 xecho(sep, v)
922     int    sep;
923     Char **v;
924 {
925     Char *cp;
926     int     nonl = 0;
927     sigset_t sigset;
928 
929     if (setintr) {
930 	sigemptyset(&sigset);
931 	(void) sigaddset(&sigset, SIGINT);
932 	(void) sigprocmask(SIG_UNBLOCK, &sigset, NULL);
933     }
934     v++;
935     if (*v == 0)
936 	return;
937     gflag = 0, tglob(v);
938     if (gflag) {
939 	v = globall(v);
940 	if (v == 0)
941 	    stderror(ERR_NAME | ERR_NOMATCH);
942     }
943     else {
944 	v = gargv = saveblk(v);
945 	trim(v);
946     }
947     if (sep == ' ' && *v && eq(*v, STRmn))
948 	nonl++, v++;
949     while ((cp = *v++) != NULL) {
950 	int c;
951 
952 	while ((c = *cp++) != '\0')
953 	    (void) vis_fputc(c | QUOTE, cshout);
954 
955 	if (*v)
956 	    (void) vis_fputc(sep | QUOTE, cshout);
957     }
958     if (sep && nonl == 0)
959 	(void) fputc('\n', cshout);
960     else
961 	(void) fflush(cshout);
962     if (setintr)
963 	(void) sigprocmask(SIG_BLOCK, &sigset, NULL);
964     if (gargv)
965 	blkfree(gargv), gargv = 0;
966 }
967 
968 void
969 /*ARGSUSED*/
970 dosetenv(v, t)
971     Char **v;
972     struct command *t;
973 {
974     Char   *vp, *lp;
975     sigset_t sigset;
976 
977     v++;
978     if ((vp = *v++) == 0) {
979 	Char **ep;
980 
981 	if (setintr) {
982 	    sigemptyset(&sigset);
983 	    (void) sigaddset(&sigset, SIGINT);
984 	    (void) sigprocmask(SIG_UNBLOCK, &sigset, NULL);
985 	}
986 	for (ep = STR_environ; *ep; ep++)
987 	    (void) fprintf(cshout, "%s\n", vis_str(*ep));
988 	return;
989     }
990     if ((lp = *v++) == 0)
991 	lp = STRNULL;
992     Setenv(vp, lp = globone(lp, G_APPEND));
993     if (eq(vp, STRPATH)) {
994 	importpath(lp);
995 	dohash(NULL, NULL);
996     }
997     else if (eq(vp, STRLANG) || eq(vp, STRLC_CTYPE)) {
998 #ifdef NLS
999 	int     k;
1000 
1001 	(void) setlocale(LC_ALL, "");
1002 	for (k = 0200; k <= 0377 && !Isprint(k); k++)
1003 		continue;
1004 	AsciiOnly = k > 0377;
1005 #else
1006 	AsciiOnly = 0;
1007 #endif				/* NLS */
1008     }
1009     xfree((ptr_t) lp);
1010 }
1011 
1012 void
1013 /*ARGSUSED*/
1014 dounsetenv(v, t)
1015     Char **v;
1016     struct command *t;
1017 {
1018     Char  **ep, *p, *n;
1019     int     i, maxi;
1020     static Char *name = NULL;
1021 
1022     if (name)
1023 	xfree((ptr_t) name);
1024     /*
1025      * Find the longest environment variable
1026      */
1027     for (maxi = 0, ep = STR_environ; *ep; ep++) {
1028 	for (i = 0, p = *ep; *p && *p != '='; p++, i++)
1029 	    continue;
1030 	if (i > maxi)
1031 	    maxi = i;
1032     }
1033 
1034     name = (Char *) xmalloc((size_t) (maxi + 1) * sizeof(Char));
1035 
1036     while (++v && *v)
1037 	for (maxi = 1; maxi;)
1038 	    for (maxi = 0, ep = STR_environ; *ep; ep++) {
1039 		for (n = name, p = *ep; *p && *p != '='; *n++ = *p++)
1040 		    continue;
1041 		*n = '\0';
1042 		if (!Gmatch(name, *v))
1043 		    continue;
1044 		maxi = 1;
1045 		if (eq(name, STRLANG) || eq(name, STRLC_CTYPE)) {
1046 #ifdef NLS
1047 		    int     k;
1048 
1049 		    (void) setlocale(LC_ALL, "");
1050 		    for (k = 0200; k <= 0377 && !Isprint(k); k++)
1051 			continue;
1052 		    AsciiOnly = k > 0377;
1053 #else
1054 		    AsciiOnly = getenv("LANG") == NULL &&
1055 			getenv("LC_CTYPE") == NULL;
1056 #endif				/* NLS */
1057 		}
1058 		/*
1059 		 * Delete name, and start again cause the environment changes
1060 		 */
1061 		Unsetenv(name);
1062 		break;
1063 	    }
1064     xfree((ptr_t) name);
1065     name = NULL;
1066 }
1067 
1068 void
1069 Setenv(name, val)
1070     Char   *name, *val;
1071 {
1072     Char **ep = STR_environ;
1073     Char *cp, *dp;
1074     Char   *blk[2];
1075     Char  **oep = ep;
1076 
1077 
1078     for (; *ep; ep++) {
1079 	for (cp = name, dp = *ep; *cp && *cp == *dp; cp++, dp++)
1080 	    continue;
1081 	if (*cp != 0 || *dp != '=')
1082 	    continue;
1083 	cp = Strspl(STRequal, val);
1084 	xfree((ptr_t) * ep);
1085 	*ep = strip(Strspl(name, cp));
1086 	xfree((ptr_t) cp);
1087 	blkfree((Char **) environ);
1088 	environ = short2blk(STR_environ);
1089 	return;
1090     }
1091     cp = Strspl(name, STRequal);
1092     blk[0] = strip(Strspl(cp, val));
1093     xfree((ptr_t) cp);
1094     blk[1] = 0;
1095     STR_environ = blkspl(STR_environ, blk);
1096     blkfree((Char **) environ);
1097     environ = short2blk(STR_environ);
1098     xfree((ptr_t) oep);
1099 }
1100 
1101 static void
1102 Unsetenv(name)
1103     Char   *name;
1104 {
1105     Char **ep = STR_environ;
1106     Char *cp, *dp;
1107     Char  **oep = ep;
1108 
1109     for (; *ep; ep++) {
1110 	for (cp = name, dp = *ep; *cp && *cp == *dp; cp++, dp++)
1111 	    continue;
1112 	if (*cp != 0 || *dp != '=')
1113 	    continue;
1114 	cp = *ep;
1115 	*ep = 0;
1116 	STR_environ = blkspl(STR_environ, ep + 1);
1117 	environ = short2blk(STR_environ);
1118 	*ep = cp;
1119 	xfree((ptr_t) cp);
1120 	xfree((ptr_t) oep);
1121 	return;
1122     }
1123 }
1124 
1125 void
1126 /*ARGSUSED*/
1127 doumask(v, t)
1128     Char **v;
1129     struct command *t;
1130 {
1131     Char *cp = v[1];
1132     int i;
1133 
1134     if (cp == 0) {
1135 	i = umask(0);
1136 	(void) umask(i);
1137 	(void) fprintf(cshout, "%o\n", i);
1138 	return;
1139     }
1140     i = 0;
1141     while (Isdigit(*cp) && *cp != '8' && *cp != '9')
1142 	i = i * 8 + *cp++ - '0';
1143     if (*cp || i < 0 || i > 0777)
1144 	stderror(ERR_NAME | ERR_MASK);
1145     (void) umask(i);
1146 }
1147 
1148 typedef quad_t RLIM_TYPE;
1149 
1150 static const struct limits {
1151     int     limconst;
1152     const   char *limname;
1153     int     limdiv;
1154     const   char *limscale;
1155 }       limits[] = {
1156     { RLIMIT_CPU,	"cputime",	1,	"seconds" },
1157     { RLIMIT_FSIZE,	"filesize",	1024,	"kbytes" },
1158     { RLIMIT_DATA,	"datasize",	1024,	"kbytes" },
1159     { RLIMIT_STACK,	"stacksize",	1024,	"kbytes" },
1160     { RLIMIT_CORE,	"coredumpsize", 1024,	"kbytes" },
1161     { RLIMIT_RSS,	"memoryuse",	1024,	"kbytes" },
1162     { RLIMIT_MEMLOCK,	"memorylocked",	1024,	"kbytes" },
1163     { RLIMIT_NPROC,	"maxproc",	1,	"" },
1164     { RLIMIT_NOFILE,	"openfiles",	1,	"" },
1165     { -1,		NULL,		0,	NULL }
1166 };
1167 
1168 static const struct limits *findlim __P((Char *));
1169 static RLIM_TYPE getval __P((const struct limits *, Char **));
1170 static void limtail __P((Char *, char *));
1171 static void plim __P((const struct limits *, Char));
1172 static int setlim __P((const struct limits *, Char, RLIM_TYPE));
1173 
1174 static const struct limits *
1175 findlim(cp)
1176     Char   *cp;
1177 {
1178     const struct limits *lp, *res;
1179 
1180     res = (struct limits *) NULL;
1181     for (lp = limits; lp->limconst >= 0; lp++)
1182 	if (prefix(cp, str2short(lp->limname))) {
1183 	    if (res)
1184 		stderror(ERR_NAME | ERR_AMBIG);
1185 	    res = lp;
1186 	}
1187     if (res)
1188 	return (res);
1189     stderror(ERR_NAME | ERR_LIMIT);
1190     /* NOTREACHED */
1191 }
1192 
1193 void
1194 /*ARGSUSED*/
1195 dolimit(v, t)
1196     Char **v;
1197     struct command *t;
1198 {
1199     const struct limits *lp;
1200     RLIM_TYPE limit;
1201     char    hard = 0;
1202 
1203     v++;
1204     if (*v && eq(*v, STRmh)) {
1205 	hard = 1;
1206 	v++;
1207     }
1208     if (*v == 0) {
1209 	for (lp = limits; lp->limconst >= 0; lp++)
1210 	    plim(lp, hard);
1211 	return;
1212     }
1213     lp = findlim(v[0]);
1214     if (v[1] == 0) {
1215 	plim(lp, hard);
1216 	return;
1217     }
1218     limit = getval(lp, v + 1);
1219     if (setlim(lp, hard, limit) < 0)
1220 	stderror(ERR_SILENT);
1221 }
1222 
1223 static  RLIM_TYPE
1224 getval(lp, v)
1225     const struct limits *lp;
1226     Char  **v;
1227 {
1228     float f;
1229     Char   *cp = *v++;
1230 
1231     f = atof(short2str(cp));
1232 
1233     while (Isdigit(*cp) || *cp == '.' || *cp == 'e' || *cp == 'E')
1234 	cp++;
1235     if (*cp == 0) {
1236 	if (*v == 0)
1237 	    return ((RLIM_TYPE) ((f + 0.5) * lp->limdiv));
1238 	cp = *v;
1239     }
1240     switch (*cp) {
1241     case ':':
1242 	if (lp->limconst != RLIMIT_CPU)
1243 	    goto badscal;
1244 	return ((RLIM_TYPE) (f * 60.0 + atof(short2str(cp + 1))));
1245     case 'h':
1246 	if (lp->limconst != RLIMIT_CPU)
1247 	    goto badscal;
1248 	limtail(cp, "hours");
1249 	f *= 3600.0;
1250 	break;
1251     case 'm':
1252 	if (lp->limconst == RLIMIT_CPU) {
1253 	    limtail(cp, "minutes");
1254 	    f *= 60.0;
1255 	    break;
1256 	}
1257 	*cp = 'm';
1258 	limtail(cp, "megabytes");
1259 	f *= 1024.0 * 1024.0;
1260 	break;
1261     case 's':
1262 	if (lp->limconst != RLIMIT_CPU)
1263 	    goto badscal;
1264 	limtail(cp, "seconds");
1265 	break;
1266     case 'M':
1267 	if (lp->limconst == RLIMIT_CPU)
1268 	    goto badscal;
1269 	*cp = 'm';
1270 	limtail(cp, "megabytes");
1271 	f *= 1024.0 * 1024.0;
1272 	break;
1273     case 'k':
1274 	if (lp->limconst == RLIMIT_CPU)
1275 	    goto badscal;
1276 	limtail(cp, "kbytes");
1277 	f *= 1024.0;
1278 	break;
1279     case 'u':
1280 	limtail(cp, "unlimited");
1281 	return (RLIM_INFINITY);
1282     default:
1283     badscal:
1284 	stderror(ERR_NAME | ERR_SCALEF);
1285 	/* NOTREACHED */
1286     }
1287     f += 0.5;
1288     if (f > (float) RLIM_INFINITY)
1289 	return RLIM_INFINITY;
1290     else
1291 	return ((RLIM_TYPE) f);
1292 }
1293 
1294 static void
1295 limtail(cp, str)
1296     Char   *cp;
1297     char   *str;
1298 {
1299     while (*cp && *cp == *str)
1300 	cp++, str++;
1301     if (*cp)
1302 	stderror(ERR_BADSCALE, str);
1303 }
1304 
1305 
1306 /*ARGSUSED*/
1307 static void
1308 plim(lp, hard)
1309     const struct limits *lp;
1310     Char    hard;
1311 {
1312     struct rlimit rlim;
1313     RLIM_TYPE limit;
1314 
1315     (void) fprintf(cshout, "%s \t", lp->limname);
1316 
1317     (void) getrlimit(lp->limconst, &rlim);
1318     limit = hard ? rlim.rlim_max : rlim.rlim_cur;
1319 
1320     if (limit == RLIM_INFINITY)
1321 	(void) fprintf(cshout, "unlimited");
1322     else if (lp->limconst == RLIMIT_CPU)
1323 	psecs((long) limit);
1324     else
1325 	(void) fprintf(cshout, "%ld %s", (long) (limit / lp->limdiv),
1326 		       lp->limscale);
1327     (void) fputc('\n', cshout);
1328 }
1329 
1330 void
1331 /*ARGSUSED*/
1332 dounlimit(v, t)
1333     Char **v;
1334     struct command *t;
1335 {
1336     const struct limits *lp;
1337     int     lerr = 0;
1338     Char    hard = 0;
1339 
1340     v++;
1341     if (*v && eq(*v, STRmh)) {
1342 	hard = 1;
1343 	v++;
1344     }
1345     if (*v == 0) {
1346 	for (lp = limits; lp->limconst >= 0; lp++)
1347 	    if (setlim(lp, hard, (RLIM_TYPE) RLIM_INFINITY) < 0)
1348 		lerr++;
1349 	if (lerr)
1350 	    stderror(ERR_SILENT);
1351 	return;
1352     }
1353     while (*v) {
1354 	lp = findlim(*v++);
1355 	if (setlim(lp, hard, (RLIM_TYPE) RLIM_INFINITY) < 0)
1356 	    stderror(ERR_SILENT);
1357     }
1358 }
1359 
1360 static int
1361 setlim(lp, hard, limit)
1362     const struct limits *lp;
1363     Char    hard;
1364     RLIM_TYPE limit;
1365 {
1366     struct rlimit rlim;
1367 
1368     (void) getrlimit(lp->limconst, &rlim);
1369 
1370     if (hard)
1371 	rlim.rlim_max = limit;
1372     else if (limit == RLIM_INFINITY && geteuid() != 0)
1373 	rlim.rlim_cur = rlim.rlim_max;
1374     else
1375 	rlim.rlim_cur = limit;
1376 
1377     if (setrlimit(lp->limconst, &rlim) < 0) {
1378 	(void) fprintf(csherr, "%s: %s: Can't %s%s limit\n", bname, lp->limname,
1379 		       limit == RLIM_INFINITY ? "remove" : "set",
1380 		       hard ? " hard" : "");
1381 	return (-1);
1382     }
1383     return (0);
1384 }
1385 
1386 void
1387 /*ARGSUSED*/
1388 dosuspend(v, t)
1389     Char **v;
1390     struct command *t;
1391 {
1392     int     ctpgrp;
1393 
1394     void    (*old) __P((int));
1395 
1396     if (loginsh)
1397 	stderror(ERR_SUSPLOG);
1398     untty();
1399 
1400     old = signal(SIGTSTP, SIG_DFL);
1401     (void) kill(0, SIGTSTP);
1402     /* the shell stops here */
1403     (void) signal(SIGTSTP, old);
1404 
1405     if (tpgrp != -1) {
1406 retry:
1407 	ctpgrp = tcgetpgrp(FSHTTY);
1408 	if  (ctpgrp != opgrp) {
1409 	    old = signal(SIGTTIN, SIG_DFL);
1410 	    (void) kill(0, SIGTTIN);
1411 	    (void) signal(SIGTTIN, old);
1412 	    goto retry;
1413 	}
1414 	(void) setpgid(0, shpgrp);
1415 	(void) tcsetpgrp(FSHTTY, shpgrp);
1416     }
1417 }
1418 
1419 /* This is the dreaded EVAL built-in.
1420  *   If you don't fiddle with file descriptors, and reset didfds,
1421  *   this command will either ignore redirection inside or outside
1422  *   its aguments, e.g. eval "date >x"  vs.  eval "date" >x
1423  *   The stuff here seems to work, but I did it by trial and error rather
1424  *   than really knowing what was going on.  If tpgrp is zero, we are
1425  *   probably a background eval, e.g. "eval date &", and we want to
1426  *   make sure that any processes we start stay in our pgrp.
1427  *   This is also the case for "time eval date" -- stay in same pgrp.
1428  *   Otherwise, under stty tostop, processes will stop in the wrong
1429  *   pgrp, with no way for the shell to get them going again.  -IAN!
1430  */
1431 static Char **gv = NULL;
1432 void
1433 /*ARGSUSED*/
1434 doeval(v, t)
1435     Char **v;
1436     struct command *t;
1437 {
1438     Char  **oevalvec;
1439     Char   *oevalp;
1440     int     odidfds;
1441     jmp_buf osetexit;
1442     int     my_reenter;
1443     Char  **savegv = gv;
1444     int     saveIN;
1445     int     saveOUT;
1446     int     saveERR;
1447     int     oSHIN;
1448     int     oSHOUT;
1449     int     oSHERR;
1450 
1451     UNREGISTER(v);
1452 
1453     oevalvec = evalvec;
1454     oevalp = evalp;
1455     odidfds = didfds;
1456     oSHIN = SHIN;
1457     oSHOUT = SHOUT;
1458     oSHERR = SHERR;
1459 
1460     v++;
1461     if (*v == 0)
1462 	return;
1463     gflag = 0, tglob(v);
1464     if (gflag) {
1465 	gv = v = globall(v);
1466 	gargv = 0;
1467 	if (v == 0)
1468 	    stderror(ERR_NOMATCH);
1469 	v = copyblk(v);
1470     }
1471     else {
1472 	gv = NULL;
1473 	v = copyblk(v);
1474 	trim(v);
1475     }
1476 
1477     saveIN = dcopy(SHIN, -1);
1478     saveOUT = dcopy(SHOUT, -1);
1479     saveERR = dcopy(SHERR, -1);
1480 
1481     getexit(osetexit);
1482 
1483     if ((my_reenter = setexit()) == 0) {
1484 	evalvec = v;
1485 	evalp = 0;
1486 	SHIN = dcopy(0, -1);
1487 	SHOUT = dcopy(1, -1);
1488 	SHERR = dcopy(2, -1);
1489 	didfds = 0;
1490 	process(0);
1491     }
1492 
1493     evalvec = oevalvec;
1494     evalp = oevalp;
1495     doneinp = 0;
1496     didfds = odidfds;
1497     (void) close(SHIN);
1498     (void) close(SHOUT);
1499     (void) close(SHERR);
1500     SHIN = dmove(saveIN, oSHIN);
1501     SHOUT = dmove(saveOUT, oSHOUT);
1502     SHERR = dmove(saveERR, oSHERR);
1503     if (gv)
1504 	blkfree(gv), gv = NULL;
1505     resexit(osetexit);
1506     gv = savegv;
1507     if (my_reenter)
1508 	stderror(ERR_SILENT);
1509 }
1510 
1511 void
1512 /*ARGSUSED*/
1513 doprintf(v, t)
1514     Char **v;
1515     struct command *t;
1516 {
1517     char **c;
1518     extern int progprintf __P((int, char **));
1519     int ret;
1520 
1521     ret = progprintf(blklen(v), c = short2blk(v));
1522     (void) fflush(cshout);
1523     (void) fflush(csherr);
1524 
1525     blkfree((Char **) c);
1526     if (ret)
1527 	stderror(ERR_SILENT);
1528 }
1529