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