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