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