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