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