csh.c revision 1.25 1 /* $NetBSD: csh.c,v 1.25 2000/05/31 22:48:44 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 __COPYRIGHT("@(#) Copyright (c) 1980, 1991, 1993\n\
39 The Regents of the University of California. All rights reserved.\n");
40 #endif /* not lint */
41
42 #ifndef lint
43 #if 0
44 static char sccsid[] = "@(#)csh.c 8.2 (Berkeley) 10/12/93";
45 #else
46 __RCSID("$NetBSD: csh.c,v 1.25 2000/05/31 22:48:44 christos Exp $");
47 #endif
48 #endif /* not lint */
49
50 #include <sys/types.h>
51 #include <sys/ioctl.h>
52 #include <sys/stat.h>
53 #include <fcntl.h>
54 #include <errno.h>
55 #include <pwd.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <time.h>
59 #include <locale.h>
60 #include <unistd.h>
61 #include <vis.h>
62 #include <paths.h> /* should this be included in pathnames.h instead? */
63 #if __STDC__
64 # include <stdarg.h>
65 #else
66 # include <varargs.h>
67 #endif
68
69 #include "csh.h"
70 #include "proc.h"
71 #include "extern.h"
72 #include "pathnames.h"
73
74 /*
75 * C Shell
76 *
77 * Bill Joy, UC Berkeley, California, USA
78 * October 1978, May 1980
79 *
80 * Jim Kulp, IIASA, Laxenburg, Austria
81 * April 1980
82 *
83 * Christos Zoulas, Cornell University
84 * June, 1991
85 */
86
87 Char *dumphist[] = {STRhistory, STRmh, 0, 0};
88 Char *loadhist[] = {STRsource, STRmh, STRtildothist, 0};
89
90 int nofile = 0;
91 bool reenter = 0;
92 bool nverbose = 0;
93 bool nexececho = 0;
94 bool quitit = 0;
95 bool fast = 0;
96 bool batch = 0;
97 bool mflag = 0;
98 bool prompt = 1;
99 bool enterhist = 0;
100
101 extern char **environ;
102
103 static int readf __P((void *, char *, int));
104 static fpos_t seekf __P((void *, fpos_t, int));
105 static int writef __P((void *, const char *, int));
106 static int closef __P((void *));
107 static int srccat __P((Char *, Char *));
108 static int srcfile __P((char *, bool, bool));
109 static void phup __P((int));
110 static void srcunit __P((int, bool, bool));
111 static void mailchk __P((void));
112 #ifndef _PATH_DEFPATH
113 static Char **defaultpath __P((void));
114 #endif
115
116 int main __P((int, char **));
117
118 int
119 main(argc, argv)
120 int argc;
121 char **argv;
122 {
123 Char *cp;
124 char *tcp;
125 const char *ecp;
126 int f;
127 char **tempv;
128 struct sigaction oact;
129 sigset_t sigset;
130
131 cshin = stdin;
132 cshout = stdout;
133 csherr = stderr;
134
135 settimes(); /* Immed. estab. timing base */
136
137 /*
138 * Initialize non constant strings
139 */
140 #ifdef _PATH_BSHELL
141 STR_BSHELL = SAVE(_PATH_BSHELL);
142 #endif
143 #ifdef _PATH_CSHELL
144 STR_SHELLPATH = SAVE(_PATH_CSHELL);
145 #endif
146 STR_environ = blk2short(environ);
147 environ = short2blk(STR_environ); /* So that we can free it */
148 STR_WORD_CHARS = SAVE(WORD_CHARS);
149
150 HIST = '!';
151 HISTSUB = '^';
152 word_chars = STR_WORD_CHARS;
153
154 tempv = argv;
155 if (eq(str2short(tempv[0]), STRaout)) /* A.out's are quittable */
156 quitit = 1;
157 uid = getuid();
158 gid = getgid();
159 euid = geteuid();
160 egid = getegid();
161 /*
162 * We are a login shell if: 1. we were invoked as -<something> and we had
163 * no arguments 2. or we were invoked only with the -l flag
164 */
165 loginsh = (**tempv == '-' && argc == 1) ||
166 (argc == 2 && tempv[1][0] == '-' && tempv[1][1] == 'l' &&
167 tempv[1][2] == '\0');
168
169 if (loginsh && **tempv != '-') {
170 /*
171 * Mangle the argv space
172 */
173 tempv[1][0] = '\0';
174 tempv[1][1] = '\0';
175 tempv[1] = NULL;
176 for (tcp = *tempv; *tcp++;)
177 continue;
178 for (tcp--; tcp >= *tempv; tcp--)
179 tcp[1] = tcp[0];
180 *++tcp = '-';
181 argc--;
182 }
183 if (loginsh)
184 (void) time(&chktim);
185
186 AsciiOnly = 1;
187 #ifdef NLS
188 (void) setlocale(LC_ALL, "");
189 {
190 int k;
191
192 for (k = 0200; k <= 0377 && !Isprint(k); k++)
193 continue;
194 AsciiOnly = k > 0377;
195 }
196 #else
197 AsciiOnly = getenv("LANG") == NULL && getenv("LC_CTYPE") == NULL;
198 #endif /* NLS */
199
200 /*
201 * Move the descriptors to safe places. The variable didfds is 0 while we
202 * have only FSH* to work with. When didfds is true, we have 0,1,2 and
203 * prefer to use these.
204 */
205 initdesc();
206 /*
207 * XXX: This is to keep programs that use stdio happy.
208 * what we really want is freunopen() ....
209 * Closing cshin cshout and csherr (which are really stdin stdout
210 * and stderr at this point and then reopening them in the same order
211 * gives us again stdin == cshin stdout == cshout and stderr == csherr.
212 * If that was not the case builtins like printf that use stdio
213 * would break. But in any case we could fix that with memcpy and
214 * a bit of pointer manipulation...
215 * Fortunately this is not needed under the current implementation
216 * of stdio.
217 */
218 (void) fclose(cshin);
219 (void) fclose(cshout);
220 (void) fclose(csherr);
221 if (!(cshin = funopen((void *) &SHIN, readf, writef, seekf, closef)))
222 exit(1);
223 if (!(cshout = funopen((void *) &SHOUT, readf, writef, seekf, closef)))
224 exit(1);
225 if (!(csherr = funopen((void *) &SHERR, readf, writef, seekf, closef)))
226 exit(1);
227 (void) setvbuf(cshin, NULL, _IOLBF, 0);
228 (void) setvbuf(cshout, NULL, _IOLBF, 0);
229 (void) setvbuf(csherr, NULL, _IOLBF, 0);
230
231 /*
232 * Initialize the shell variables. ARGV and PROMPT are initialized later.
233 * STATUS is also munged in several places. CHILD is munged when
234 * forking/waiting
235 */
236 set(STRstatus, Strsave(STR0));
237
238 if ((ecp = getenv("HOME")) != NULL)
239 cp = quote(SAVE(ecp));
240 else
241 cp = NULL;
242
243 if (cp == NULL)
244 fast = 1; /* No home -> can't read scripts */
245 else
246 set(STRhome, cp);
247 dinit(cp); /* dinit thinks that HOME == cwd in a login
248 * shell */
249 /*
250 * Grab other useful things from the environment. Should we grab
251 * everything??
252 */
253 if ((ecp = getenv("LOGNAME")) != NULL ||
254 (ecp = getenv("USER")) != NULL)
255 set(STRuser, quote(SAVE(ecp)));
256 if ((ecp = getenv("TERM")) != NULL)
257 set(STRterm, quote(SAVE(ecp)));
258
259 /*
260 * Re-initialize path if set in environment
261 */
262 if ((ecp = getenv("PATH")) == NULL) {
263 #ifdef _PATH_DEFPATH
264 importpath(SAVE(_PATH_DEFPATH));
265 #else
266 setq(STRpath, defaultpath(), &shvhed);
267 #endif
268 } else {
269 importpath(SAVE(ecp));
270 }
271
272 set(STRshell, Strsave(STR_SHELLPATH));
273
274 doldol = putn((int) getpid()); /* For $$ */
275 shtemp = Strspl(STRtmpsh, doldol); /* For << */
276
277 /*
278 * Record the interrupt states from the parent process. If the parent is
279 * non-interruptible our hand must be forced or we (and our children) won't
280 * be either. Our children inherit termination from our parent. We catch it
281 * only if we are the login shell.
282 */
283 /* parents interruptibility */
284 (void) sigaction(SIGINT, NULL, &oact);
285 parintr = oact.sa_handler;
286 (void) sigaction(SIGTERM, NULL, &oact);
287 parterm = oact.sa_handler;
288
289 /* catch these all, login shell or not */
290 (void) signal(SIGHUP, phup); /* exit processing on HUP */
291 (void) signal(SIGXCPU, phup); /* ...and on XCPU */
292 (void) signal(SIGXFSZ, phup); /* ...and on XFSZ */
293
294 /*
295 * Process the arguments.
296 *
297 * Note that processing of -v/-x is actually delayed till after script
298 * processing.
299 *
300 * We set the first character of our name to be '-' if we are a shell
301 * running interruptible commands. Many programs which examine ps'es
302 * use this to filter such shells out.
303 */
304 argc--, tempv++;
305 while (argc > 0 && (tcp = tempv[0])[0] == '-' && *++tcp != '\0' && !batch) {
306 do
307 switch (*tcp++) {
308
309 case 0: /* - Interruptible, no prompt */
310 prompt = 0;
311 setintr = 1;
312 nofile = 1;
313 break;
314
315 case 'b': /* -b Next arg is input file */
316 batch = 1;
317 break;
318
319 case 'c': /* -c Command input from arg */
320 if (argc == 1)
321 xexit(0);
322 argc--, tempv++;
323 arginp = SAVE(tempv[0]);
324 prompt = 0;
325 nofile = 1;
326 break;
327
328 case 'e': /* -e Exit on any error */
329 exiterr = 1;
330 break;
331
332 case 'f': /* -f Fast start */
333 fast = 1;
334 break;
335
336 case 'i': /* -i Interactive, even if !intty */
337 intact = 1;
338 nofile = 1;
339 break;
340
341 case 'm': /* -m read .cshrc (from su) */
342 mflag = 1;
343 break;
344
345 case 'n': /* -n Don't execute */
346 noexec = 1;
347 break;
348
349 case 'q': /* -q (Undoc'd) ... die on quit */
350 quitit = 1;
351 break;
352
353 case 's': /* -s Read from std input */
354 nofile = 1;
355 break;
356
357 case 't': /* -t Read one line from input */
358 onelflg = 2;
359 prompt = 0;
360 nofile = 1;
361 break;
362
363 case 'v': /* -v Echo hist expanded input */
364 nverbose = 1; /* ... later */
365 break;
366
367 case 'x': /* -x Echo just before execution */
368 nexececho = 1; /* ... later */
369 break;
370
371 case 'V': /* -V Echo hist expanded input */
372 setNS(STRverbose); /* NOW! */
373 break;
374
375 case 'X': /* -X Echo just before execution */
376 setNS(STRecho); /* NOW! */
377 break;
378
379 } while (*tcp);
380 tempv++, argc--;
381 }
382
383 if (quitit) /* With all due haste, for debugging */
384 (void) signal(SIGQUIT, SIG_DFL);
385
386 /*
387 * Unless prevented by -, -c, -i, -s, or -t, if there are remaining
388 * arguments the first of them is the name of a shell file from which to
389 * read commands.
390 */
391 if (nofile == 0 && argc > 0) {
392 nofile = open(tempv[0], O_RDONLY);
393 if (nofile < 0) {
394 child = 1; /* So this doesn't return */
395 stderror(ERR_SYSTEM, tempv[0], strerror(errno));
396 }
397 ffile = SAVE(tempv[0]);
398 /*
399 * Replace FSHIN. Handle /dev/std{in,out,err} specially
400 * since once they are closed we cannot open them again.
401 * In that case we use our own saved descriptors
402 */
403 if ((SHIN = dmove(nofile, FSHIN)) < 0)
404 switch(nofile) {
405 case 0:
406 SHIN = FSHIN;
407 break;
408 case 1:
409 SHIN = FSHOUT;
410 break;
411 case 2:
412 SHIN = FSHERR;
413 break;
414 default:
415 stderror(ERR_SYSTEM, tempv[0], strerror(errno));
416 /* NOTREACHED */
417 }
418 (void) ioctl(SHIN, FIOCLEX, NULL);
419 prompt = 0;
420 /* argc not used any more */ tempv++;
421 }
422
423 intty = isatty(SHIN);
424 intty |= intact;
425 if (intty || (intact && isatty(SHOUT))) {
426 if (!batch && (uid != euid || gid != egid)) {
427 errno = EACCES;
428 child = 1; /* So this doesn't return */
429 stderror(ERR_SYSTEM, "csh", strerror(errno));
430 }
431 }
432 /*
433 * Decide whether we should play with signals or not. If we are explicitly
434 * told (via -i, or -) or we are a login shell (arg0 starts with -) or the
435 * input and output are both the ttys("csh", or "csh</dev/ttyx>/dev/ttyx")
436 * Note that in only the login shell is it likely that parent may have set
437 * signals to be ignored
438 */
439 if (loginsh || intact || (intty && isatty(SHOUT)))
440 setintr = 1;
441 settell();
442 /*
443 * Save the remaining arguments in argv.
444 */
445 setq(STRargv, blk2short(tempv), &shvhed);
446
447 /*
448 * Set up the prompt.
449 */
450 if (prompt) {
451 set(STRprompt, Strsave(uid == 0 ? STRsymhash : STRsymcent));
452 /* that's a meta-questionmark */
453 set(STRprompt2, Strsave(STRmquestion));
454 }
455
456 /*
457 * If we are an interactive shell, then start fiddling with the signals;
458 * this is a tricky game.
459 */
460 shpgrp = getpgrp();
461 opgrp = tpgrp = -1;
462 if (setintr) {
463 **argv = '-';
464 if (!quitit) /* Wary! */
465 (void) signal(SIGQUIT, SIG_IGN);
466 (void) signal(SIGINT, pintr);
467 sigemptyset(&sigset);
468 (void) sigaddset(&sigset, SIGINT);
469 (void) sigprocmask(SIG_BLOCK, &sigset, NULL);
470 (void) signal(SIGTERM, SIG_IGN);
471 if (quitit == 0 && arginp == 0) {
472 (void) signal(SIGTSTP, SIG_IGN);
473 (void) signal(SIGTTIN, SIG_IGN);
474 (void) signal(SIGTTOU, SIG_IGN);
475 /*
476 * Wait till in foreground, in case someone stupidly runs csh &
477 * dont want to try to grab away the tty.
478 */
479 if (isatty(FSHERR))
480 f = FSHERR;
481 else if (isatty(FSHOUT))
482 f = FSHOUT;
483 else if (isatty(OLDSTD))
484 f = OLDSTD;
485 else
486 f = -1;
487 retry:
488 if ((tpgrp = tcgetpgrp(f)) != -1) {
489 if (tpgrp != shpgrp) {
490 sig_t old = signal(SIGTTIN, SIG_DFL);
491 (void) kill(0, SIGTTIN);
492 (void) signal(SIGTTIN, old);
493 goto retry;
494 }
495 opgrp = shpgrp;
496 shpgrp = getpid();
497 tpgrp = shpgrp;
498 /*
499 * Setpgid will fail if we are a session leader and
500 * mypid == mypgrp (POSIX 4.3.3)
501 */
502 if (opgrp != shpgrp)
503 if (setpgid(0, shpgrp) == -1)
504 goto notty;
505 /*
506 * We do that after we set our process group, to make sure
507 * that the process group belongs to a process in the same
508 * session as the tty (our process and our group) (POSIX 7.2.4)
509 */
510 if (tcsetpgrp(f, shpgrp) == -1)
511 goto notty;
512 (void) ioctl(dcopy(f, FSHTTY), FIOCLEX, NULL);
513 }
514 if (tpgrp == -1) {
515 notty:
516 (void) fprintf(csherr, "Warning: no access to tty (%s).\n",
517 strerror(errno));
518 (void) fprintf(csherr, "Thus no job control in this shell.\n");
519 }
520 }
521 }
522 if ((setintr == 0) && (parintr == SIG_DFL))
523 setintr = 1;
524 (void) signal(SIGCHLD, pchild); /* while signals not ready */
525
526 /*
527 * Set an exit here in case of an interrupt or error reading the shell
528 * start-up scripts.
529 */
530 reenter = setexit(); /* PWP */
531 haderr = 0; /* In case second time through */
532 if (!fast && reenter == 0) {
533 /* Will have value(STRhome) here because set fast if don't */
534 {
535 int osetintr = setintr;
536 sig_t oparintr = parintr;
537 sigset_t osigset;
538
539 sigemptyset(&sigset);
540 (void) sigaddset(&sigset, SIGINT);
541 (void) sigprocmask(SIG_BLOCK, &sigset, &osigset);
542
543 setintr = 0;
544 parintr = SIG_IGN; /* Disable onintr */
545 #ifdef _PATH_DOTCSHRC
546 (void) srcfile(_PATH_DOTCSHRC, 0, 0);
547 #endif
548 if (!fast && !arginp && !onelflg)
549 dohash(NULL, NULL);
550 #ifdef _PATH_DOTLOGIN
551 if (loginsh)
552 (void) srcfile(_PATH_DOTLOGIN, 0, 0);
553 #endif
554 (void) sigprocmask(SIG_SETMASK, &osigset, NULL);
555 setintr = osetintr;
556 parintr = oparintr;
557 }
558 (void) srccat(value(STRhome), STRsldotcshrc);
559
560 if (!fast && !arginp && !onelflg && !havhash)
561 dohash(NULL, NULL);
562 /*
563 * Source history before .login so that it is available in .login
564 */
565 if ((cp = value(STRhistfile)) != STRNULL)
566 loadhist[2] = cp;
567 dosource(loadhist, NULL);
568 if (loginsh)
569 (void) srccat(value(STRhome), STRsldotlogin);
570 }
571
572 /*
573 * Now are ready for the -v and -x flags
574 */
575 if (nverbose)
576 setNS(STRverbose);
577 if (nexececho)
578 setNS(STRecho);
579
580 /*
581 * All the rest of the world is inside this call. The argument to process
582 * indicates whether it should catch "error unwinds". Thus if we are a
583 * interactive shell our call here will never return by being blown past on
584 * an error.
585 */
586 process(setintr);
587
588 /*
589 * Mop-up.
590 */
591 if (intty) {
592 if (loginsh) {
593 (void) fprintf(cshout, "logout\n");
594 (void) close(SHIN);
595 child = 1;
596 goodbye();
597 }
598 else {
599 (void) fprintf(cshout, "exit\n");
600 }
601 }
602 rechist();
603 exitstat();
604 /* NOTREACHED */
605 }
606
607 void
608 untty()
609 {
610 if (tpgrp > 0) {
611 (void) setpgid(0, opgrp);
612 (void) tcsetpgrp(FSHTTY, opgrp);
613 }
614 }
615
616 void
617 importpath(cp)
618 Char *cp;
619 {
620 int i = 0;
621 Char *dp;
622 Char **pv;
623 int c;
624
625 for (dp = cp; *dp; dp++)
626 if (*dp == ':')
627 i++;
628 /*
629 * i+2 where i is the number of colons in the path. There are i+1
630 * directories in the path plus we need room for a zero terminator.
631 */
632 pv = (Char **) xcalloc((size_t) (i + 2), sizeof(Char **));
633 dp = cp;
634 i = 0;
635 if (*dp)
636 for (;;) {
637 if ((c = *dp) == ':' || c == 0) {
638 *dp = 0;
639 pv[i++] = Strsave(*cp ? cp : STRdot);
640 if (c) {
641 cp = dp + 1;
642 *dp = ':';
643 }
644 else
645 break;
646 }
647 dp++;
648 }
649 pv[i] = 0;
650 set1(STRpath, pv, &shvhed);
651 }
652
653 /*
654 * Source to the file which is the catenation of the argument names.
655 */
656 static int
657 srccat(cp, dp)
658 Char *cp, *dp;
659 {
660 Char *ep = Strspl(cp, dp);
661 char *ptr = short2str(ep);
662
663 xfree((ptr_t) ep);
664 return srcfile(ptr, mflag ? 0 : 1, 0);
665 }
666
667 /*
668 * Source to a file putting the file descriptor in a safe place (> 2).
669 */
670 static int
671 srcfile(f, onlyown, flag)
672 char *f;
673 bool onlyown, flag;
674 {
675 int unit;
676
677 if ((unit = open(f, O_RDONLY)) == -1)
678 return 0;
679 unit = dmove(unit, -1);
680
681 (void) ioctl(unit, FIOCLEX, NULL);
682 srcunit(unit, onlyown, flag);
683 return 1;
684 }
685
686 /*
687 * Source to a unit. If onlyown it must be our file or our group or
688 * we don't chance it. This occurs on ".cshrc"s and the like.
689 */
690 int insource;
691 static void
692 srcunit(unit, onlyown, hflg)
693 int unit;
694 bool onlyown, hflg;
695 {
696 /* We have to push down a lot of state here */
697 /* All this could go into a structure */
698 int oSHIN = -1, oldintty = intty, oinsource = insource;
699 struct whyle *oldwhyl = whyles;
700 Char *ogointr = gointr, *oarginp = arginp;
701 Char *oevalp = evalp, **oevalvec = evalvec;
702 int oonelflg = onelflg;
703 bool oenterhist = enterhist;
704 char OHIST = HIST;
705 bool otell = cantell;
706
707 struct Bin saveB;
708 sigset_t sigset, osigset;
709 jmp_buf oldexit;
710
711 /* The (few) real local variables */
712 int my_reenter;
713
714 if (unit < 0)
715 return;
716 if (didfds)
717 donefds();
718 if (onlyown) {
719 struct stat stb;
720
721 if (fstat(unit, &stb) < 0) {
722 (void) close(unit);
723 return;
724 }
725 }
726
727 /*
728 * There is a critical section here while we are pushing down the input
729 * stream since we have stuff in different structures. If we weren't
730 * careful an interrupt could corrupt SHIN's Bin structure and kill the
731 * shell.
732 *
733 * We could avoid the critical region by grouping all the stuff in a single
734 * structure and pointing at it to move it all at once. This is less
735 * efficient globally on many variable references however.
736 */
737 insource = 1;
738 getexit(oldexit);
739
740 if (setintr) {
741 sigemptyset(&sigset);
742 (void) sigaddset(&sigset, SIGINT);
743 (void) sigprocmask(SIG_BLOCK, &sigset, &osigset);
744 }
745 /* Setup the new values of the state stuff saved above */
746 (void) memcpy(&saveB, &B, sizeof(B));
747 fbuf = NULL;
748 fseekp = feobp = fblocks = 0;
749 oSHIN = SHIN, SHIN = unit, arginp = 0, onelflg = 0;
750 intty = isatty(SHIN), whyles = 0, gointr = 0;
751 evalvec = 0;
752 evalp = 0;
753 enterhist = hflg;
754 if (enterhist)
755 HIST = '\0';
756
757 /*
758 * Now if we are allowing commands to be interrupted, we let ourselves be
759 * interrupted.
760 */
761 if (setintr)
762 (void) sigprocmask(SIG_SETMASK, &osigset, NULL);
763 settell();
764
765 if ((my_reenter = setexit()) == 0)
766 process(0); /* 0 -> blow away on errors */
767
768 if (setintr)
769 (void) sigprocmask(SIG_SETMASK, &osigset, NULL);
770 if (oSHIN >= 0) {
771 int i;
772
773 /* We made it to the new state... free up its storage */
774 /* This code could get run twice but xfree doesn't care */
775 for (i = 0; i < fblocks; i++)
776 xfree((ptr_t) fbuf[i]);
777 xfree((ptr_t) fbuf);
778
779 /* Reset input arena */
780 (void) memcpy(&B, &saveB, sizeof(B));
781
782 (void) close(SHIN), SHIN = oSHIN;
783 arginp = oarginp, onelflg = oonelflg;
784 evalp = oevalp, evalvec = oevalvec;
785 intty = oldintty, whyles = oldwhyl, gointr = ogointr;
786 if (enterhist)
787 HIST = OHIST;
788 enterhist = oenterhist;
789 cantell = otell;
790 }
791
792 resexit(oldexit);
793 /*
794 * If process reset() (effectively an unwind) then we must also unwind.
795 */
796 if (my_reenter)
797 stderror(ERR_SILENT);
798 insource = oinsource;
799 }
800
801 void
802 rechist()
803 {
804 Char buf[BUFSIZE], hbuf[BUFSIZE], *hfile;
805 int fp, ftmp, oldidfds;
806 struct varent *shist;
807
808 if (!fast) {
809 /*
810 * If $savehist is just set, we use the value of $history
811 * else we use the value in $savehist
812 */
813 if ((shist = adrof(STRsavehist)) != NULL) {
814 if (shist->vec[0][0] != '\0')
815 (void) Strcpy(hbuf, shist->vec[0]);
816 else if ((shist = adrof(STRhistory)) && shist->vec[0][0] != '\0')
817 (void) Strcpy(hbuf, shist->vec[0]);
818 else
819 return;
820 }
821 else
822 return;
823
824 if ((hfile = value(STRhistfile)) == STRNULL) {
825 hfile = Strcpy(buf, value(STRhome));
826 (void) Strcat(buf, STRsldthist);
827 }
828
829 if ((fp = open(short2str(hfile), O_WRONLY | O_CREAT | O_TRUNC,
830 0600)) == -1)
831 return;
832
833 oldidfds = didfds;
834 didfds = 0;
835 ftmp = SHOUT;
836 SHOUT = fp;
837 dumphist[2] = hbuf;
838 dohist(dumphist, NULL);
839 SHOUT = ftmp;
840 (void) close(fp);
841 didfds = oldidfds;
842 }
843 }
844
845 void
846 goodbye()
847 {
848 rechist();
849
850 if (loginsh) {
851 (void) signal(SIGQUIT, SIG_IGN);
852 (void) signal(SIGINT, SIG_IGN);
853 (void) signal(SIGTERM, SIG_IGN);
854 setintr = 0; /* No interrupts after "logout" */
855 if (!(adrof(STRlogout)))
856 set(STRlogout, STRnormal);
857 #ifdef _PATH_DOTLOGOUT
858 (void) srcfile(_PATH_DOTLOGOUT, 0, 0);
859 #endif
860 if (adrof(STRhome))
861 (void) srccat(value(STRhome), STRsldtlogout);
862 }
863 exitstat();
864 /* NOTREACHED */
865 }
866
867 __dead void
868 exitstat()
869 {
870 Char *s;
871 #ifdef PROF
872 monitor(0);
873 #endif
874 /*
875 * Note that if STATUS is corrupted (i.e. getn bombs) then error will exit
876 * directly because we poke child here. Otherwise we might continue
877 * unwarrantedly (sic).
878 */
879 child = 1;
880 s = value(STRstatus);
881 xexit(s ? getn(s) : 0);
882 /* NOTREACHED */
883 }
884
885 /*
886 * in the event of a HUP we want to save the history
887 */
888 static void
889 phup(sig)
890 int sig;
891 {
892 rechist();
893
894 /*
895 * We kill the last foreground process group. It then becomes
896 * responsible to propagate the SIGHUP to its progeny.
897 */
898 {
899 struct process *pp, *np;
900
901 for (pp = proclist.p_next; pp; pp = pp->p_next) {
902 np = pp;
903 /*
904 * Find if this job is in the foreground. It could be that
905 * the process leader has exited and the foreground flag
906 * is cleared for it.
907 */
908 do
909 /*
910 * If a process is in the foreground; we try to kill
911 * it's process group. If we succeed, then the
912 * whole job is gone. Otherwise we keep going...
913 * But avoid sending HUP to the shell again.
914 */
915 if ((np->p_flags & PFOREGND) != 0 && np->p_jobid != shpgrp &&
916 kill(-np->p_jobid, SIGHUP) != -1) {
917 /* In case the job was suspended... */
918 (void) kill(-np->p_jobid, SIGCONT);
919 break;
920 }
921 while ((np = np->p_friends) != pp);
922 }
923 }
924 xexit(sig);
925 /* NOTREACHED */
926 }
927
928 Char *jobargv[2] = {STRjobs, 0};
929
930 /*
931 * Catch an interrupt, e.g. during lexical input.
932 * If we are an interactive shell, we reset the interrupt catch
933 * immediately. In any case we drain the shell output,
934 * and finally go through the normal error mechanism, which
935 * gets a chance to make the shell go away.
936 */
937 /* ARGSUSED */
938 void
939 pintr(notused)
940 int notused;
941 {
942 pintr1(1);
943 /* NOTREACHED */
944 }
945
946 void
947 pintr1(wantnl)
948 bool wantnl;
949 {
950 Char **v;
951 sigset_t sigset, osigset;
952
953 sigemptyset(&sigset);
954 (void) sigprocmask(SIG_BLOCK, &sigset, &osigset);
955 if (setintr) {
956 sigset = osigset;
957 (void) sigdelset(&sigset, SIGINT);
958 (void) sigprocmask(SIG_SETMASK, &sigset, NULL);
959 if (pjobs) {
960 pjobs = 0;
961 (void) fprintf(cshout, "\n");
962 dojobs(jobargv, NULL);
963 stderror(ERR_NAME | ERR_INTR);
964 }
965 }
966 (void) sigdelset(&osigset, SIGCHLD);
967 (void) sigprocmask(SIG_SETMASK, &osigset, NULL);
968 (void) fpurge(cshout);
969 (void) endpwent();
970
971 /*
972 * If we have an active "onintr" then we search for the label. Note that if
973 * one does "onintr -" then we shan't be interruptible so we needn't worry
974 * about that here.
975 */
976 if (gointr) {
977 gotolab(gointr);
978 timflg = 0;
979 if ((v = pargv) != NULL)
980 pargv = 0, blkfree(v);
981 if ((v = gargv) != NULL)
982 gargv = 0, blkfree(v);
983 reset();
984 }
985 else if (intty && wantnl) {
986 (void) fputc('\r', cshout);
987 (void) fputc('\n', cshout);
988 }
989 stderror(ERR_SILENT);
990 /* NOTREACHED */
991 }
992
993 /*
994 * Process is the main driving routine for the shell.
995 * It runs all command processing, except for those within { ... }
996 * in expressions (which is run by a routine evalav in sh.exp.c which
997 * is a stripped down process), and `...` evaluation which is run
998 * also by a subset of this code in sh.glob.c in the routine backeval.
999 *
1000 * The code here is a little strange because part of it is interruptible
1001 * and hence freeing of structures appears to occur when none is necessary
1002 * if this is ignored.
1003 *
1004 * Note that if catch is not set then we will unwind on any error.
1005 * If an end-of-file occurs, we return.
1006 */
1007 static struct command *savet = NULL;
1008 void
1009 process(catch)
1010 bool catch;
1011 {
1012 jmp_buf osetexit;
1013 struct command *t = savet;
1014 sigset_t sigset;
1015
1016 savet = NULL;
1017 getexit(osetexit);
1018 for (;;) {
1019 pendjob();
1020 paraml.next = paraml.prev = ¶ml;
1021 paraml.word = STRNULL;
1022 (void) setexit();
1023 justpr = enterhist; /* execute if not entering history */
1024
1025 /*
1026 * Interruptible during interactive reads
1027 */
1028 if (setintr) {
1029 sigemptyset(&sigset);
1030 (void) sigaddset(&sigset, SIGINT);
1031 (void) sigprocmask(SIG_UNBLOCK, &sigset, NULL);
1032 }
1033
1034 /*
1035 * For the sake of reset()
1036 */
1037 freelex(¶ml);
1038 if (savet)
1039 freesyn(savet), savet = NULL;
1040
1041 if (haderr) {
1042 if (!catch) {
1043 /* unwind */
1044 doneinp = 0;
1045 resexit(osetexit);
1046 savet = t;
1047 reset();
1048 }
1049 haderr = 0;
1050 /*
1051 * Every error is eventually caught here or the shell dies. It is
1052 * at this point that we clean up any left-over open files, by
1053 * closing all but a fixed number of pre-defined files. Thus
1054 * routines don't have to worry about leaving files open due to
1055 * deeper errors... they will get closed here.
1056 */
1057 closem();
1058 continue;
1059 }
1060 if (doneinp) {
1061 doneinp = 0;
1062 break;
1063 }
1064 if (chkstop)
1065 chkstop--;
1066 if (neednote)
1067 pnote();
1068 if (intty && prompt && evalvec == 0) {
1069 mailchk();
1070 /*
1071 * If we are at the end of the input buffer then we are going to
1072 * read fresh stuff. Otherwise, we are rereading input and don't
1073 * need or want to prompt.
1074 */
1075 if (aret == F_SEEK && fseekp == feobp)
1076 printprompt();
1077 (void) fflush(cshout);
1078 }
1079 if (seterr) {
1080 xfree((ptr_t) seterr);
1081 seterr = NULL;
1082 }
1083
1084 /*
1085 * Echo not only on VERBOSE, but also with history expansion. If there
1086 * is a lexical error then we forego history echo.
1087 */
1088 if ((lex(¶ml) && !seterr && intty) || adrof(STRverbose)) {
1089 prlex(csherr, ¶ml);
1090 }
1091
1092 /*
1093 * The parser may lose space if interrupted.
1094 */
1095 if (setintr)
1096 (void) sigprocmask(SIG_BLOCK, &sigset, NULL);
1097
1098 /*
1099 * Save input text on the history list if reading in old history, or it
1100 * is from the terminal at the top level and not in a loop.
1101 *
1102 * PWP: entry of items in the history list while in a while loop is done
1103 * elsewhere...
1104 */
1105 if (enterhist || (catch && intty && !whyles))
1106 savehist(¶ml);
1107
1108 /*
1109 * Print lexical error messages, except when sourcing history lists.
1110 */
1111 if (!enterhist && seterr)
1112 stderror(ERR_OLD);
1113
1114 /*
1115 * If had a history command :p modifier then this is as far as we
1116 * should go
1117 */
1118 if (justpr)
1119 reset();
1120
1121 alias(¶ml);
1122
1123 /*
1124 * Parse the words of the input into a parse tree.
1125 */
1126 savet = syntax(paraml.next, ¶ml, 0);
1127 if (seterr)
1128 stderror(ERR_OLD);
1129
1130 execute(savet, (tpgrp > 0 ? tpgrp : -1), NULL, NULL);
1131
1132 /*
1133 * Made it!
1134 */
1135 freelex(¶ml);
1136 freesyn((struct command *) savet), savet = NULL;
1137 }
1138 resexit(osetexit);
1139 savet = t;
1140 }
1141
1142 void
1143 /*ARGSUSED*/
1144 dosource(v, t)
1145 Char **v;
1146 struct command *t;
1147
1148 {
1149 Char *f;
1150 bool hflg = 0;
1151 Char buf[BUFSIZE];
1152
1153 v++;
1154 if (*v && eq(*v, STRmh)) {
1155 if (*++v == NULL)
1156 stderror(ERR_NAME | ERR_HFLAG);
1157 hflg++;
1158 }
1159 (void) Strcpy(buf, *v);
1160 f = globone(buf, G_ERROR);
1161 (void) strcpy((char *) buf, short2str(f));
1162 xfree((ptr_t) f);
1163 if (!srcfile((char *) buf, 0, hflg) && !hflg)
1164 stderror(ERR_SYSTEM, (char *) buf, strerror(errno));
1165 }
1166
1167 /*
1168 * Check for mail.
1169 * If we are a login shell, then we don't want to tell
1170 * about any mail file unless its been modified
1171 * after the time we started.
1172 * This prevents us from telling the user things he already
1173 * knows, since the login program insists on saying
1174 * "You have mail."
1175 */
1176 static void
1177 mailchk()
1178 {
1179 struct varent *v;
1180 Char **vp;
1181 time_t t;
1182 int intvl, cnt;
1183 struct stat stb;
1184 bool new;
1185
1186 v = adrof(STRmail);
1187 if (v == 0)
1188 return;
1189 (void) time(&t);
1190 vp = v->vec;
1191 cnt = blklen(vp);
1192 intvl = (cnt && number(*vp)) ? (--cnt, getn(*vp++)) : MAILINTVL;
1193 if (intvl < 1)
1194 intvl = 1;
1195 if (chktim + intvl > t)
1196 return;
1197 for (; *vp; vp++) {
1198 if (stat(short2str(*vp), &stb) < 0)
1199 continue;
1200 new = stb.st_mtime > time0.tv_sec;
1201 if (stb.st_size == 0 || stb.st_atime > stb.st_mtime ||
1202 (stb.st_atime < chktim && stb.st_mtime < chktim) ||
1203 (loginsh && !new))
1204 continue;
1205 if (cnt == 1)
1206 (void) fprintf(cshout, "You have %smail.\n", new ? "new " : "");
1207 else
1208 (void) fprintf(cshout, "%s in %s.\n", new ? "New mail" : "Mail",
1209 vis_str(*vp));
1210 }
1211 chktim = t;
1212 }
1213
1214 /*
1215 * Extract a home directory from the password file
1216 * The argument points to a buffer where the name of the
1217 * user whose home directory is sought is currently.
1218 * We write the home directory of the user back there.
1219 */
1220 int
1221 gethdir(home)
1222 Char *home;
1223 {
1224 Char *h;
1225 struct passwd *pw;
1226
1227 /*
1228 * Is it us?
1229 */
1230 if (*home == '\0') {
1231 if ((h = value(STRhome)) != NULL) {
1232 (void) Strcpy(home, h);
1233 return 0;
1234 }
1235 else
1236 return 1;
1237 }
1238
1239 if ((pw = getpwnam(short2str(home))) != NULL) {
1240 (void) Strcpy(home, str2short(pw->pw_dir));
1241 return 0;
1242 }
1243 else
1244 return 1;
1245 }
1246
1247 /*
1248 * When didfds is set, we do I/O from 0, 1, 2 otherwise from 15, 16, 17
1249 * We also check if the shell has already changed the decriptor to point to
1250 * 0, 1, 2 when didfds is set.
1251 */
1252 #define DESC(a) (*((int *) (a)) - (didfds && *((int *) a) >= FSHIN ? FSHIN : 0))
1253
1254 static int
1255 readf(oreo, buf, siz)
1256 void *oreo;
1257 char *buf;
1258 int siz;
1259 {
1260 return read(DESC(oreo), buf, siz);
1261 }
1262
1263
1264 static int
1265 writef(oreo, buf, siz)
1266 void *oreo;
1267 const char *buf;
1268 int siz;
1269 {
1270 return write(DESC(oreo), buf, siz);
1271 }
1272
1273 static fpos_t
1274 seekf(oreo, off, whence)
1275 void *oreo;
1276 fpos_t off;
1277 int whence;
1278 {
1279 return lseek(DESC(oreo), off, whence);
1280 }
1281
1282
1283 static int
1284 closef(oreo)
1285 void *oreo;
1286 {
1287 return close(DESC(oreo));
1288 }
1289
1290
1291 /*
1292 * Print the visible version of a string.
1293 */
1294 int
1295 vis_fputc(ch, fp)
1296 int ch;
1297 FILE *fp;
1298 {
1299 char uenc[5]; /* 4 + NULL */
1300
1301 if (ch & QUOTE)
1302 return fputc(ch & TRIM, fp);
1303 /*
1304 * XXX: When we are in AsciiOnly we want all characters >= 0200 to
1305 * be encoded, but currently there is no way in vis to do that.
1306 */
1307 (void) vis(uenc, ch & TRIM, VIS_NOSLASH, 0);
1308 return fputs(uenc, fp);
1309 }
1310
1311 /*
1312 * Move the initial descriptors to their eventual
1313 * resting places, closin all other units.
1314 */
1315 void
1316 initdesc()
1317 {
1318
1319 didfds = 0; /* 0, 1, 2 aren't set up */
1320 (void) ioctl(SHIN = dcopy(0, FSHIN), FIOCLEX, NULL);
1321 (void) ioctl(SHOUT = dcopy(1, FSHOUT), FIOCLEX, NULL);
1322 (void) ioctl(SHERR = dcopy(2, FSHERR), FIOCLEX, NULL);
1323 (void) ioctl(OLDSTD = dcopy(SHIN, FOLDSTD), FIOCLEX, NULL);
1324 closem();
1325 }
1326
1327
1328 __dead void
1329 #ifdef PROF
1330 done(i)
1331 #else
1332 xexit(i)
1333 #endif
1334 int i;
1335 {
1336 untty();
1337 _exit(i);
1338 /* NOTREACHED */
1339 }
1340
1341 #ifndef _PATH_DEFPATH
1342 static Char **
1343 defaultpath()
1344 {
1345 char *ptr;
1346 Char **blk, **blkp;
1347 struct stat stb;
1348
1349 blkp = blk = (Char **) xmalloc((size_t) sizeof(Char *) * 10);
1350
1351 #define DIRAPPEND(a) \
1352 if (stat(ptr = a, &stb) == 0 && S_ISDIR(stb.st_mode)) \
1353 *blkp++ = SAVE(ptr)
1354
1355 DIRAPPEND(_PATH_BIN);
1356 DIRAPPEND(_PATH_USRBIN);
1357
1358 #undef DIRAPPEND
1359
1360 #if 0
1361 if (euid != 0 && uid != 0)
1362 *blkp++ = Strsave(STRdot);
1363 #endif
1364
1365 *blkp = NULL;
1366 return (blk);
1367 }
1368 #endif /* _PATH_DEFPATH */
1369
1370 void
1371 printprompt()
1372 {
1373 Char *cp;
1374
1375 if (!whyles) {
1376 for (cp = value(STRprompt); *cp; cp++)
1377 if (*cp == HIST)
1378 (void) fprintf(cshout, "%d", eventno + 1);
1379 else {
1380 if (*cp == '\\' && cp[1] == HIST)
1381 cp++;
1382 (void) vis_fputc(*cp | QUOTE, cshout);
1383 }
1384 }
1385 else
1386 /*
1387 * Prompt for forward reading loop body content.
1388 */
1389 (void) fprintf(cshout, "? ");
1390 (void) fflush(cshout);
1391 }
1392