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