csh.c revision 1.20 1 /* $NetBSD: csh.c,v 1.20 1998/07/27 15:32:04 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.20 1998/07/27 15:32:04 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 argc--, tempv++;
327 arginp = SAVE(tempv[0]);
328 prompt = 0;
329 nofile = 1;
330 break;
331
332 case 'e': /* -e Exit on any error */
333 exiterr = 1;
334 break;
335
336 case 'f': /* -f Fast start */
337 fast = 1;
338 break;
339
340 case 'i': /* -i Interactive, even if !intty */
341 intact = 1;
342 nofile = 1;
343 break;
344
345 case 'm': /* -m read .cshrc (from su) */
346 mflag = 1;
347 break;
348
349 case 'n': /* -n Don't execute */
350 noexec = 1;
351 break;
352
353 case 'q': /* -q (Undoc'd) ... die on quit */
354 quitit = 1;
355 break;
356
357 case 's': /* -s Read from std input */
358 nofile = 1;
359 break;
360
361 case 't': /* -t Read one line from input */
362 onelflg = 2;
363 prompt = 0;
364 nofile = 1;
365 break;
366
367 case 'v': /* -v Echo hist expanded input */
368 nverbose = 1; /* ... later */
369 break;
370
371 case 'x': /* -x Echo just before execution */
372 nexececho = 1; /* ... later */
373 break;
374
375 case 'V': /* -V Echo hist expanded input */
376 setNS(STRverbose); /* NOW! */
377 break;
378
379 case 'X': /* -X Echo just before execution */
380 setNS(STRecho); /* NOW! */
381 break;
382
383 } while (*tcp);
384 tempv++, argc--;
385 }
386
387 if (quitit) /* With all due haste, for debugging */
388 (void) signal(SIGQUIT, SIG_DFL);
389
390 /*
391 * Unless prevented by -, -c, -i, -s, or -t, if there are remaining
392 * arguments the first of them is the name of a shell file from which to
393 * read commands.
394 */
395 if (nofile == 0 && argc > 0) {
396 nofile = open(tempv[0], O_RDONLY);
397 if (nofile < 0) {
398 child = 1; /* So this doesn't return */
399 stderror(ERR_SYSTEM, tempv[0], strerror(errno));
400 }
401 ffile = SAVE(tempv[0]);
402 /*
403 * Replace FSHIN. Handle /dev/std{in,out,err} specially
404 * since once they are closed we cannot open them again.
405 * In that case we use our own saved descriptors
406 */
407 if ((SHIN = dmove(nofile, FSHIN)) < 0)
408 switch(nofile) {
409 case 0:
410 SHIN = FSHIN;
411 break;
412 case 1:
413 SHIN = FSHOUT;
414 break;
415 case 2:
416 SHIN = FSHERR;
417 break;
418 default:
419 stderror(ERR_SYSTEM, tempv[0], strerror(errno));
420 break;
421 }
422 (void) ioctl(SHIN, FIOCLEX, NULL);
423 prompt = 0;
424 /* argc not used any more */ tempv++;
425 }
426
427 intty = isatty(SHIN);
428 intty |= intact;
429 if (intty || (intact && isatty(SHOUT))) {
430 if (!batch && (uid != euid || gid != egid)) {
431 errno = EACCES;
432 child = 1; /* So this doesn't return */
433 stderror(ERR_SYSTEM, "csh", strerror(errno));
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 sigaddset(&sigset, SIGINT);
473 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 sigaddset(&sigset, SIGINT);
545 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 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 return (0);
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 sigaddset(&sigset, SIGINT);
747 sigprocmask(SIG_BLOCK, &sigset, &osigset);
748 }
749 /* Setup the new values of the state stuff saved above */
750 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 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 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 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 insource = oinsource;
803 }
804
805 void
806 rechist()
807 {
808 Char buf[BUFSIZ], hbuf[BUFSIZ], *hfile;
809 int fp, ftmp, oldidfds;
810 struct varent *shist;
811
812 if (!fast) {
813 /*
814 * If $savehist is just set, we use the value of $history
815 * else we use the value in $savehist
816 */
817 if ((shist = adrof(STRsavehist)) != NULL) {
818 if (shist->vec[0][0] != '\0')
819 (void) Strcpy(hbuf, shist->vec[0]);
820 else if ((shist = adrof(STRhistory)) && shist->vec[0][0] != '\0')
821 (void) Strcpy(hbuf, shist->vec[0]);
822 else
823 return;
824 }
825 else
826 return;
827
828 if ((hfile = value(STRhistfile)) == STRNULL) {
829 hfile = Strcpy(buf, value(STRhome));
830 (void) Strcat(buf, STRsldthist);
831 }
832
833 if ((fp = open(short2str(hfile), O_WRONLY | O_CREAT | O_TRUNC,
834 0600)) == -1)
835 return;
836
837 oldidfds = didfds;
838 didfds = 0;
839 ftmp = SHOUT;
840 SHOUT = fp;
841 dumphist[2] = hbuf;
842 dohist(dumphist, NULL);
843 SHOUT = ftmp;
844 (void) close(fp);
845 didfds = oldidfds;
846 }
847 }
848
849 void
850 goodbye()
851 {
852 rechist();
853
854 if (loginsh) {
855 (void) signal(SIGQUIT, SIG_IGN);
856 (void) signal(SIGINT, SIG_IGN);
857 (void) signal(SIGTERM, SIG_IGN);
858 setintr = 0; /* No interrupts after "logout" */
859 if (!(adrof(STRlogout)))
860 set(STRlogout, STRnormal);
861 #ifdef _PATH_DOTLOGOUT
862 (void) srcfile(_PATH_DOTLOGOUT, 0, 0);
863 #endif
864 if (adrof(STRhome))
865 (void) srccat(value(STRhome), STRsldtlogout);
866 }
867 exitstat();
868 }
869
870 void
871 exitstat()
872 {
873 Char *s;
874 #ifdef PROF
875 monitor(0);
876 #endif
877 /*
878 * Note that if STATUS is corrupted (i.e. getn bombs) then error will exit
879 * directly because we poke child here. Otherwise we might continue
880 * unwarrantedly (sic).
881 */
882 child = 1;
883 s = value(STRstatus);
884 xexit(s ? getn(s) : 0);
885 }
886
887 /*
888 * in the event of a HUP we want to save the history
889 */
890 static void
891 phup(sig)
892 int sig;
893 {
894 rechist();
895
896 /*
897 * We kill the last foreground process group. It then becomes
898 * responsible to propagate the SIGHUP to its progeny.
899 */
900 {
901 struct process *pp, *np;
902
903 for (pp = proclist.p_next; pp; pp = pp->p_next) {
904 np = pp;
905 /*
906 * Find if this job is in the foreground. It could be that
907 * the process leader has exited and the foreground flag
908 * is cleared for it.
909 */
910 do
911 /*
912 * If a process is in the foreground; we try to kill
913 * it's process group. If we succeed, then the
914 * whole job is gone. Otherwise we keep going...
915 * But avoid sending HUP to the shell again.
916 */
917 if ((np->p_flags & PFOREGND) != 0 && np->p_jobid != shpgrp &&
918 kill(-np->p_jobid, SIGHUP) != -1) {
919 /* In case the job was suspended... */
920 (void) kill(-np->p_jobid, SIGCONT);
921 break;
922 }
923 while ((np = np->p_friends) != pp);
924 }
925 }
926 xexit(sig);
927 }
928
929 Char *jobargv[2] = {STRjobs, 0};
930
931 /*
932 * Catch an interrupt, e.g. during lexical input.
933 * If we are an interactive shell, we reset the interrupt catch
934 * immediately. In any case we drain the shell output,
935 * and finally go through the normal error mechanism, which
936 * gets a chance to make the shell go away.
937 */
938 /* ARGSUSED */
939 void
940 pintr(notused)
941 int notused;
942 {
943 pintr1(1);
944 }
945
946 void
947 pintr1(wantnl)
948 bool wantnl;
949 {
950 Char **v;
951 sigset_t sigset, osigset;
952
953 sigemptyset(&sigset);
954 sigprocmask(SIG_BLOCK, &sigset, &osigset);
955 if (setintr) {
956 sigset = osigset;
957 sigdelset(&sigset, SIGINT);
958 sigprocmask(SIG_SETMASK, &sigset, NULL);
959 if (pjobs) {
960 pjobs = 0;
961 (void) fprintf(cshout, "\n");
962 dojobs(jobargv, NULL);
963 stderror(ERR_NAME | ERR_INTR);
964 }
965 }
966 sigdelset(&osigset, SIGCHLD);
967 sigprocmask(SIG_SETMASK, &osigset, NULL);
968 (void) fpurge(cshout);
969 (void) endpwent();
970
971 /*
972 * If we have an active "onintr" then we search for the label. Note that if
973 * one does "onintr -" then we shan't be interruptible so we needn't worry
974 * about that here.
975 */
976 if (gointr) {
977 gotolab(gointr);
978 timflg = 0;
979 if ((v = pargv) != NULL)
980 pargv = 0, blkfree(v);
981 if ((v = gargv) != NULL)
982 gargv = 0, blkfree(v);
983 reset();
984 }
985 else if (intty && wantnl) {
986 (void) fputc('\r', cshout);
987 (void) fputc('\n', cshout);
988 }
989 stderror(ERR_SILENT);
990 }
991
992 /*
993 * Process is the main driving routine for the shell.
994 * It runs all command processing, except for those within { ... }
995 * in expressions (which is run by a routine evalav in sh.exp.c which
996 * is a stripped down process), and `...` evaluation which is run
997 * also by a subset of this code in sh.glob.c in the routine backeval.
998 *
999 * The code here is a little strange because part of it is interruptible
1000 * and hence freeing of structures appears to occur when none is necessary
1001 * if this is ignored.
1002 *
1003 * Note that if catch is not set then we will unwind on any error.
1004 * If an end-of-file occurs, we return.
1005 */
1006 static struct command *savet = NULL;
1007 void
1008 process(catch)
1009 bool catch;
1010 {
1011 jmp_buf osetexit;
1012 struct command *t = savet;
1013 sigset_t sigset;
1014
1015 savet = NULL;
1016 getexit(osetexit);
1017 for (;;) {
1018 pendjob();
1019 paraml.next = paraml.prev = ¶ml;
1020 paraml.word = STRNULL;
1021 (void) setexit();
1022 justpr = enterhist; /* execute if not entering history */
1023
1024 /*
1025 * Interruptible during interactive reads
1026 */
1027 if (setintr) {
1028 sigemptyset(&sigset);
1029 sigaddset(&sigset, SIGINT);
1030 sigprocmask(SIG_UNBLOCK, &sigset, NULL);
1031 }
1032
1033 /*
1034 * For the sake of reset()
1035 */
1036 freelex(¶ml);
1037 if (savet)
1038 freesyn(savet), savet = NULL;
1039
1040 if (haderr) {
1041 if (!catch) {
1042 /* unwind */
1043 doneinp = 0;
1044 resexit(osetexit);
1045 savet = t;
1046 reset();
1047 }
1048 haderr = 0;
1049 /*
1050 * Every error is eventually caught here or the shell dies. It is
1051 * at this point that we clean up any left-over open files, by
1052 * closing all but a fixed number of pre-defined files. Thus
1053 * routines don't have to worry about leaving files open due to
1054 * deeper errors... they will get closed here.
1055 */
1056 closem();
1057 continue;
1058 }
1059 if (doneinp) {
1060 doneinp = 0;
1061 break;
1062 }
1063 if (chkstop)
1064 chkstop--;
1065 if (neednote)
1066 pnote();
1067 if (intty && prompt && evalvec == 0) {
1068 mailchk();
1069 /*
1070 * If we are at the end of the input buffer then we are going to
1071 * read fresh stuff. Otherwise, we are rereading input and don't
1072 * need or want to prompt.
1073 */
1074 if (aret == F_SEEK && fseekp == feobp)
1075 printprompt();
1076 (void) fflush(cshout);
1077 }
1078 if (seterr) {
1079 xfree((ptr_t) seterr);
1080 seterr = NULL;
1081 }
1082
1083 /*
1084 * Echo not only on VERBOSE, but also with history expansion. If there
1085 * is a lexical error then we forego history echo.
1086 */
1087 if ((lex(¶ml) && !seterr && intty) || adrof(STRverbose)) {
1088 prlex(csherr, ¶ml);
1089 }
1090
1091 /*
1092 * The parser may lose space if interrupted.
1093 */
1094 if (setintr)
1095 sigprocmask(SIG_BLOCK, &sigset, NULL);
1096
1097 /*
1098 * Save input text on the history list if reading in old history, or it
1099 * is from the terminal at the top level and not in a loop.
1100 *
1101 * PWP: entry of items in the history list while in a while loop is done
1102 * elsewhere...
1103 */
1104 if (enterhist || (catch && intty && !whyles))
1105 savehist(¶ml);
1106
1107 /*
1108 * Print lexical error messages, except when sourcing history lists.
1109 */
1110 if (!enterhist && seterr)
1111 stderror(ERR_OLD);
1112
1113 /*
1114 * If had a history command :p modifier then this is as far as we
1115 * should go
1116 */
1117 if (justpr)
1118 reset();
1119
1120 alias(¶ml);
1121
1122 /*
1123 * Parse the words of the input into a parse tree.
1124 */
1125 savet = syntax(paraml.next, ¶ml, 0);
1126 if (seterr)
1127 stderror(ERR_OLD);
1128
1129 execute(savet, (tpgrp > 0 ? tpgrp : -1), NULL, NULL);
1130
1131 /*
1132 * Made it!
1133 */
1134 freelex(¶ml);
1135 freesyn((struct command *) savet), savet = NULL;
1136 }
1137 resexit(osetexit);
1138 savet = t;
1139 }
1140
1141 void
1142 /*ARGSUSED*/
1143 dosource(v, t)
1144 Char **v;
1145 struct command *t;
1146
1147 {
1148 Char *f;
1149 bool hflg = 0;
1150 Char buf[BUFSIZ];
1151
1152 v++;
1153 if (*v && eq(*v, STRmh)) {
1154 if (*++v == NULL)
1155 stderror(ERR_NAME | ERR_HFLAG);
1156 hflg++;
1157 }
1158 (void) Strcpy(buf, *v);
1159 f = globone(buf, G_ERROR);
1160 (void) strcpy((char *) buf, short2str(f));
1161 xfree((ptr_t) f);
1162 if (!srcfile((char *) buf, 0, hflg) && !hflg)
1163 stderror(ERR_SYSTEM, (char *) buf, strerror(errno));
1164 }
1165
1166 /*
1167 * Check for mail.
1168 * If we are a login shell, then we don't want to tell
1169 * about any mail file unless its been modified
1170 * after the time we started.
1171 * This prevents us from telling the user things he already
1172 * knows, since the login program insists on saying
1173 * "You have mail."
1174 */
1175 static void
1176 mailchk()
1177 {
1178 struct varent *v;
1179 Char **vp;
1180 time_t t;
1181 int intvl, cnt;
1182 struct stat stb;
1183 bool new;
1184
1185 v = adrof(STRmail);
1186 if (v == 0)
1187 return;
1188 (void) time(&t);
1189 vp = v->vec;
1190 cnt = blklen(vp);
1191 intvl = (cnt && number(*vp)) ? (--cnt, getn(*vp++)) : MAILINTVL;
1192 if (intvl < 1)
1193 intvl = 1;
1194 if (chktim + intvl > t)
1195 return;
1196 for (; *vp; vp++) {
1197 if (stat(short2str(*vp), &stb) < 0)
1198 continue;
1199 new = stb.st_mtime > time0.tv_sec;
1200 if (stb.st_size == 0 || stb.st_atime > stb.st_mtime ||
1201 (stb.st_atime < chktim && stb.st_mtime < chktim) ||
1202 (loginsh && !new))
1203 continue;
1204 if (cnt == 1)
1205 (void) fprintf(cshout, "You have %smail.\n", new ? "new " : "");
1206 else
1207 (void) fprintf(cshout, "%s in %s.\n", new ? "New mail" : "Mail",
1208 vis_str(*vp));
1209 }
1210 chktim = t;
1211 }
1212
1213 /*
1214 * Extract a home directory from the password file
1215 * The argument points to a buffer where the name of the
1216 * user whose home directory is sought is currently.
1217 * We write the home directory of the user back there.
1218 */
1219 int
1220 gethdir(home)
1221 Char *home;
1222 {
1223 Char *h;
1224 struct passwd *pw;
1225
1226 /*
1227 * Is it us?
1228 */
1229 if (*home == '\0') {
1230 if ((h = value(STRhome)) != NULL) {
1231 (void) Strcpy(home, h);
1232 return 0;
1233 }
1234 else
1235 return 1;
1236 }
1237
1238 if ((pw = getpwnam(short2str(home))) != NULL) {
1239 (void) Strcpy(home, str2short(pw->pw_dir));
1240 return 0;
1241 }
1242 else
1243 return 1;
1244 }
1245
1246 /*
1247 * When didfds is set, we do I/O from 0, 1, 2 otherwise from 15, 16, 17
1248 * We also check if the shell has already changed the decriptor to point to
1249 * 0, 1, 2 when didfds is set.
1250 */
1251 #define DESC(a) (*((int *) (a)) - (didfds && *((int *) a) >= FSHIN ? FSHIN : 0))
1252
1253 static int
1254 readf(oreo, buf, siz)
1255 void *oreo;
1256 char *buf;
1257 int siz;
1258 {
1259 return read(DESC(oreo), buf, siz);
1260 }
1261
1262
1263 static int
1264 writef(oreo, buf, siz)
1265 void *oreo;
1266 const char *buf;
1267 int siz;
1268 {
1269 return write(DESC(oreo), buf, siz);
1270 }
1271
1272 static fpos_t
1273 seekf(oreo, off, whence)
1274 void *oreo;
1275 fpos_t off;
1276 int whence;
1277 {
1278 return lseek(DESC(oreo), off, whence);
1279 }
1280
1281
1282 static int
1283 closef(oreo)
1284 void *oreo;
1285 {
1286 return close(DESC(oreo));
1287 }
1288
1289
1290 /*
1291 * Print the visible version of a string.
1292 */
1293 int
1294 vis_fputc(ch, fp)
1295 int ch;
1296 FILE *fp;
1297 {
1298 char uenc[5]; /* 4 + NULL */
1299
1300 if (ch & QUOTE)
1301 return fputc(ch & TRIM, fp);
1302 /*
1303 * XXX: When we are in AsciiOnly we want all characters >= 0200 to
1304 * be encoded, but currently there is no way in vis to do that.
1305 */
1306 (void) vis(uenc, ch & TRIM, VIS_NOSLASH, 0);
1307 return fputs(uenc, fp);
1308 }
1309
1310 /*
1311 * Move the initial descriptors to their eventual
1312 * resting places, closin all other units.
1313 */
1314 void
1315 initdesc()
1316 {
1317
1318 didfds = 0; /* 0, 1, 2 aren't set up */
1319 (void) ioctl(SHIN = dcopy(0, FSHIN), FIOCLEX, NULL);
1320 (void) ioctl(SHOUT = dcopy(1, FSHOUT), FIOCLEX, NULL);
1321 (void) ioctl(SHERR = dcopy(2, FSHERR), FIOCLEX, NULL);
1322 (void) ioctl(OLDSTD = dcopy(SHIN, FOLDSTD), FIOCLEX, NULL);
1323 closem();
1324 }
1325
1326
1327 void
1328 #ifdef PROF
1329 done(i)
1330 #else
1331 xexit(i)
1332 #endif
1333 int i;
1334 {
1335 untty();
1336 _exit(i);
1337 }
1338
1339 #ifndef _PATH_DEFPATH
1340 static Char **
1341 defaultpath()
1342 {
1343 char *ptr;
1344 Char **blk, **blkp;
1345 struct stat stb;
1346
1347 blkp = blk = (Char **) xmalloc((size_t) sizeof(Char *) * 10);
1348
1349 #define DIRAPPEND(a) \
1350 if (stat(ptr = a, &stb) == 0 && S_ISDIR(stb.st_mode)) \
1351 *blkp++ = SAVE(ptr)
1352
1353 DIRAPPEND(_PATH_BIN);
1354 DIRAPPEND(_PATH_USRBIN);
1355
1356 #undef DIRAPPEND
1357
1358 #if 0
1359 if (euid != 0 && uid != 0)
1360 *blkp++ = Strsave(STRdot);
1361 #endif
1362
1363 *blkp = NULL;
1364 return (blk);
1365 }
1366 #endif /* _PATH_DEFPATH */
1367
1368 void
1369 printprompt()
1370 {
1371 Char *cp;
1372
1373 if (!whyles) {
1374 for (cp = value(STRprompt); *cp; cp++)
1375 if (*cp == HIST)
1376 (void) fprintf(cshout, "%d", eventno + 1);
1377 else {
1378 if (*cp == '\\' && cp[1] == HIST)
1379 cp++;
1380 (void) vis_fputc(*cp | QUOTE, cshout);
1381 }
1382 }
1383 else
1384 /*
1385 * Prompt for forward reading loop body content.
1386 */
1387 (void) fprintf(cshout, "? ");
1388 (void) fflush(cshout);
1389 }
1390