csh.c revision 1.8 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.8 1994/09/23 11:16:28 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 if ((*cp != '/' || *cp == '\0') && (euid == 0 || uid == 0))
620 (void) fprintf(csherr,
621 "Warning: imported path contains relative components\n");
622 pv[i++] = Strsave(*cp ? cp : STRdot);
623 if (c) {
624 cp = dp + 1;
625 *dp = ':';
626 }
627 else
628 break;
629 }
630 dp++;
631 }
632 pv[i] = 0;
633 set1(STRpath, pv, &shvhed);
634 }
635
636 /*
637 * Source to the file which is the catenation of the argument names.
638 */
639 static int
640 srccat(cp, dp)
641 Char *cp, *dp;
642 {
643 register Char *ep = Strspl(cp, dp);
644 char *ptr = short2str(ep);
645
646 xfree((ptr_t) ep);
647 return srcfile(ptr, mflag ? 0 : 1, 0);
648 }
649
650 /*
651 * Source to a file putting the file descriptor in a safe place (> 2).
652 */
653 static int
654 srcfile(f, onlyown, flag)
655 char *f;
656 bool onlyown, flag;
657 {
658 register int unit;
659
660 if ((unit = open(f, O_RDONLY)) == -1)
661 return 0;
662 unit = dmove(unit, -1);
663
664 (void) ioctl(unit, FIOCLEX, NULL);
665 srcunit(unit, onlyown, flag);
666 return 1;
667 }
668
669 /*
670 * Source to a unit. If onlyown it must be our file or our group or
671 * we don't chance it. This occurs on ".cshrc"s and the like.
672 */
673 int insource;
674 static void
675 srcunit(unit, onlyown, hflg)
676 register int unit;
677 bool onlyown, hflg;
678 {
679 /* We have to push down a lot of state here */
680 /* All this could go into a structure */
681 int oSHIN = -1, oldintty = intty, oinsource = insource;
682 struct whyle *oldwhyl = whyles;
683 Char *ogointr = gointr, *oarginp = arginp;
684 Char *oevalp = evalp, **oevalvec = evalvec;
685 int oonelflg = onelflg;
686 bool oenterhist = enterhist;
687 char OHIST = HIST;
688 bool otell = cantell;
689
690 struct Bin saveB;
691 volatile sigset_t omask;
692 jmp_buf oldexit;
693
694 /* The (few) real local variables */
695 int my_reenter;
696
697 if (unit < 0)
698 return;
699 if (didfds)
700 donefds();
701 if (onlyown) {
702 struct stat stb;
703
704 if (fstat(unit, &stb) < 0) {
705 (void) close(unit);
706 return;
707 }
708 }
709
710 /*
711 * There is a critical section here while we are pushing down the input
712 * stream since we have stuff in different structures. If we weren't
713 * careful an interrupt could corrupt SHIN's Bin structure and kill the
714 * shell.
715 *
716 * We could avoid the critical region by grouping all the stuff in a single
717 * structure and pointing at it to move it all at once. This is less
718 * efficient globally on many variable references however.
719 */
720 insource = 1;
721 getexit(oldexit);
722 omask = 0;
723
724 if (setintr)
725 omask = sigblock(sigmask(SIGINT));
726 /* Setup the new values of the state stuff saved above */
727 memcpy(&saveB, &B, sizeof(B));
728 fbuf = NULL;
729 fseekp = feobp = fblocks = 0;
730 oSHIN = SHIN, SHIN = unit, arginp = 0, onelflg = 0;
731 intty = isatty(SHIN), whyles = 0, gointr = 0;
732 evalvec = 0;
733 evalp = 0;
734 enterhist = hflg;
735 if (enterhist)
736 HIST = '\0';
737
738 /*
739 * Now if we are allowing commands to be interrupted, we let ourselves be
740 * interrupted.
741 */
742 if (setintr)
743 (void) sigsetmask(omask);
744 settell();
745
746 if ((my_reenter = setexit()) == 0)
747 process(0); /* 0 -> blow away on errors */
748
749 if (setintr)
750 (void) sigsetmask(omask);
751 if (oSHIN >= 0) {
752 register int i;
753
754 /* We made it to the new state... free up its storage */
755 /* This code could get run twice but xfree doesn't care */
756 for (i = 0; i < fblocks; i++)
757 xfree((ptr_t) fbuf[i]);
758 xfree((ptr_t) fbuf);
759
760 /* Reset input arena */
761 memcpy(&B, &saveB, sizeof(B));
762
763 (void) close(SHIN), SHIN = oSHIN;
764 arginp = oarginp, onelflg = oonelflg;
765 evalp = oevalp, evalvec = oevalvec;
766 intty = oldintty, whyles = oldwhyl, gointr = ogointr;
767 if (enterhist)
768 HIST = OHIST;
769 enterhist = oenterhist;
770 cantell = otell;
771 }
772
773 resexit(oldexit);
774 /*
775 * If process reset() (effectively an unwind) then we must also unwind.
776 */
777 if (my_reenter)
778 stderror(ERR_SILENT);
779 insource = oinsource;
780 }
781
782 void
783 rechist()
784 {
785 Char buf[BUFSIZ], hbuf[BUFSIZ], *hfile;
786 int fp, ftmp, oldidfds;
787 struct varent *shist;
788
789 if (!fast) {
790 /*
791 * If $savehist is just set, we use the value of $history
792 * else we use the value in $savehist
793 */
794 if ((shist = adrof(STRsavehist)) != NULL) {
795 if (shist->vec[0][0] != '\0')
796 (void) Strcpy(hbuf, shist->vec[0]);
797 else if ((shist = adrof(STRhistory)) && shist->vec[0][0] != '\0')
798 (void) Strcpy(hbuf, shist->vec[0]);
799 else
800 return;
801 }
802 else
803 return;
804
805 if ((hfile = value(STRhistfile)) == STRNULL) {
806 hfile = Strcpy(buf, value(STRhome));
807 (void) Strcat(buf, STRsldthist);
808 }
809
810 if ((fp = open(short2str(hfile), O_WRONLY | O_CREAT | O_TRUNC,
811 0600)) == -1)
812 return;
813
814 oldidfds = didfds;
815 didfds = 0;
816 ftmp = SHOUT;
817 SHOUT = fp;
818 dumphist[2] = hbuf;
819 dohist(dumphist, NULL);
820 SHOUT = ftmp;
821 (void) close(fp);
822 didfds = oldidfds;
823 }
824 }
825
826 void
827 goodbye()
828 {
829 rechist();
830
831 if (loginsh) {
832 (void) signal(SIGQUIT, SIG_IGN);
833 (void) signal(SIGINT, SIG_IGN);
834 (void) signal(SIGTERM, SIG_IGN);
835 setintr = 0; /* No interrupts after "logout" */
836 if (!(adrof(STRlogout)))
837 set(STRlogout, STRnormal);
838 #ifdef _PATH_DOTLOGOUT
839 (void) srcfile(_PATH_DOTLOGOUT, 0, 0);
840 #endif
841 if (adrof(STRhome))
842 (void) srccat(value(STRhome), STRsldtlogout);
843 }
844 exitstat();
845 }
846
847 void
848 exitstat()
849 {
850 Char *s;
851 #ifdef PROF
852 monitor(0);
853 #endif
854 /*
855 * Note that if STATUS is corrupted (i.e. getn bombs) then error will exit
856 * directly because we poke child here. Otherwise we might continue
857 * unwarrantedly (sic).
858 */
859 child = 1;
860 s = value(STRstatus);
861 xexit(s ? getn(s) : 0);
862 }
863
864 /*
865 * in the event of a HUP we want to save the history
866 */
867 static void
868 phup(sig)
869 int sig;
870 {
871 rechist();
872
873 /*
874 * We kill the last foreground process group. It then becomes
875 * responsible to propagate the SIGHUP to its progeny.
876 */
877 {
878 struct process *pp, *np;
879
880 for (pp = proclist.p_next; pp; pp = pp->p_next) {
881 np = pp;
882 /*
883 * Find if this job is in the foreground. It could be that
884 * the process leader has exited and the foreground flag
885 * is cleared for it.
886 */
887 do
888 /*
889 * If a process is in the foreground; we try to kill
890 * it's process group. If we succeed, then the
891 * whole job is gone. Otherwise we keep going...
892 * But avoid sending HUP to the shell again.
893 */
894 if ((np->p_flags & PFOREGND) != 0 && np->p_jobid != shpgrp &&
895 killpg(np->p_jobid, SIGHUP) != -1) {
896 /* In case the job was suspended... */
897 (void) killpg(np->p_jobid, SIGCONT);
898 break;
899 }
900 while ((np = np->p_friends) != pp);
901 }
902 }
903 xexit(sig);
904 }
905
906 Char *jobargv[2] = {STRjobs, 0};
907
908 /*
909 * Catch an interrupt, e.g. during lexical input.
910 * If we are an interactive shell, we reset the interrupt catch
911 * immediately. In any case we drain the shell output,
912 * and finally go through the normal error mechanism, which
913 * gets a chance to make the shell go away.
914 */
915 /* ARGSUSED */
916 void
917 pintr(notused)
918 int notused;
919 {
920 pintr1(1);
921 }
922
923 void
924 pintr1(wantnl)
925 bool wantnl;
926 {
927 Char **v;
928 sigset_t omask;
929
930 omask = sigblock((sigset_t) 0);
931 if (setintr) {
932 (void) sigsetmask(omask & ~sigmask(SIGINT));
933 if (pjobs) {
934 pjobs = 0;
935 (void) fprintf(cshout, "\n");
936 dojobs(jobargv, NULL);
937 stderror(ERR_NAME | ERR_INTR);
938 }
939 }
940 (void) sigsetmask(omask & ~sigmask(SIGCHLD));
941 (void) fpurge(cshout);
942 (void) endpwent();
943
944 /*
945 * If we have an active "onintr" then we search for the label. Note that if
946 * one does "onintr -" then we shan't be interruptible so we needn't worry
947 * about that here.
948 */
949 if (gointr) {
950 gotolab(gointr);
951 timflg = 0;
952 if ((v = pargv) != NULL)
953 pargv = 0, blkfree(v);
954 if ((v = gargv) != NULL)
955 gargv = 0, blkfree(v);
956 reset();
957 }
958 else if (intty && wantnl) {
959 (void) fputc('\r', cshout);
960 (void) fputc('\n', cshout);
961 }
962 stderror(ERR_SILENT);
963 }
964
965 /*
966 * Process is the main driving routine for the shell.
967 * It runs all command processing, except for those within { ... }
968 * in expressions (which is run by a routine evalav in sh.exp.c which
969 * is a stripped down process), and `...` evaluation which is run
970 * also by a subset of this code in sh.glob.c in the routine backeval.
971 *
972 * The code here is a little strange because part of it is interruptible
973 * and hence freeing of structures appears to occur when none is necessary
974 * if this is ignored.
975 *
976 * Note that if catch is not set then we will unwind on any error.
977 * If an end-of-file occurs, we return.
978 */
979 static struct command *savet = NULL;
980 void
981 process(catch)
982 bool catch;
983 {
984 jmp_buf osetexit;
985 struct command *t = savet;
986
987 savet = NULL;
988 getexit(osetexit);
989 for (;;) {
990 pendjob();
991 paraml.next = paraml.prev = ¶ml;
992 paraml.word = STRNULL;
993 (void) setexit();
994 justpr = enterhist; /* execute if not entering history */
995
996 /*
997 * Interruptible during interactive reads
998 */
999 if (setintr)
1000 (void) sigsetmask(sigblock((sigset_t) 0) & ~sigmask(SIGINT));
1001
1002 /*
1003 * For the sake of reset()
1004 */
1005 freelex(¶ml);
1006 if (savet)
1007 freesyn(savet), savet = NULL;
1008
1009 if (haderr) {
1010 if (!catch) {
1011 /* unwind */
1012 doneinp = 0;
1013 resexit(osetexit);
1014 savet = t;
1015 reset();
1016 }
1017 haderr = 0;
1018 /*
1019 * Every error is eventually caught here or the shell dies. It is
1020 * at this point that we clean up any left-over open files, by
1021 * closing all but a fixed number of pre-defined files. Thus
1022 * routines don't have to worry about leaving files open due to
1023 * deeper errors... they will get closed here.
1024 */
1025 closem();
1026 continue;
1027 }
1028 if (doneinp) {
1029 doneinp = 0;
1030 break;
1031 }
1032 if (chkstop)
1033 chkstop--;
1034 if (neednote)
1035 pnote();
1036 if (intty && prompt && evalvec == 0) {
1037 mailchk();
1038 /*
1039 * If we are at the end of the input buffer then we are going to
1040 * read fresh stuff. Otherwise, we are rereading input and don't
1041 * need or want to prompt.
1042 */
1043 if (aret == F_SEEK && fseekp == feobp)
1044 printprompt();
1045 (void) fflush(cshout);
1046 }
1047 if (seterr) {
1048 xfree((ptr_t) seterr);
1049 seterr = NULL;
1050 }
1051
1052 /*
1053 * Echo not only on VERBOSE, but also with history expansion. If there
1054 * is a lexical error then we forego history echo.
1055 */
1056 if ((lex(¶ml) && !seterr && intty) || adrof(STRverbose)) {
1057 prlex(csherr, ¶ml);
1058 }
1059
1060 /*
1061 * The parser may lose space if interrupted.
1062 */
1063 if (setintr)
1064 (void) sigblock(sigmask(SIGINT));
1065
1066 /*
1067 * Save input text on the history list if reading in old history, or it
1068 * is from the terminal at the top level and not in a loop.
1069 *
1070 * PWP: entry of items in the history list while in a while loop is done
1071 * elsewhere...
1072 */
1073 if (enterhist || (catch && intty && !whyles))
1074 savehist(¶ml);
1075
1076 /*
1077 * Print lexical error messages, except when sourcing history lists.
1078 */
1079 if (!enterhist && seterr)
1080 stderror(ERR_OLD);
1081
1082 /*
1083 * If had a history command :p modifier then this is as far as we
1084 * should go
1085 */
1086 if (justpr)
1087 reset();
1088
1089 alias(¶ml);
1090
1091 /*
1092 * Parse the words of the input into a parse tree.
1093 */
1094 savet = syntax(paraml.next, ¶ml, 0);
1095 if (seterr)
1096 stderror(ERR_OLD);
1097
1098 execute(savet, (tpgrp > 0 ? tpgrp : -1), NULL, NULL);
1099
1100 /*
1101 * Made it!
1102 */
1103 freelex(¶ml);
1104 freesyn((struct command *) savet), savet = NULL;
1105 }
1106 resexit(osetexit);
1107 savet = t;
1108 }
1109
1110 void
1111 /*ARGSUSED*/
1112 dosource(v, t)
1113 Char **v;
1114 struct command *t;
1115
1116 {
1117 register Char *f;
1118 bool hflg = 0;
1119 Char buf[BUFSIZ];
1120
1121 v++;
1122 if (*v && eq(*v, STRmh)) {
1123 if (*++v == NULL)
1124 stderror(ERR_NAME | ERR_HFLAG);
1125 hflg++;
1126 }
1127 (void) Strcpy(buf, *v);
1128 f = globone(buf, G_ERROR);
1129 (void) strcpy((char *) buf, short2str(f));
1130 xfree((ptr_t) f);
1131 if (!srcfile((char *) buf, 0, hflg) && !hflg)
1132 stderror(ERR_SYSTEM, (char *) buf, strerror(errno));
1133 }
1134
1135 /*
1136 * Check for mail.
1137 * If we are a login shell, then we don't want to tell
1138 * about any mail file unless its been modified
1139 * after the time we started.
1140 * This prevents us from telling the user things he already
1141 * knows, since the login program insists on saying
1142 * "You have mail."
1143 */
1144 static void
1145 mailchk()
1146 {
1147 register struct varent *v;
1148 register Char **vp;
1149 time_t t;
1150 int intvl, cnt;
1151 struct stat stb;
1152 bool new;
1153
1154 v = adrof(STRmail);
1155 if (v == 0)
1156 return;
1157 (void) time(&t);
1158 vp = v->vec;
1159 cnt = blklen(vp);
1160 intvl = (cnt && number(*vp)) ? (--cnt, getn(*vp++)) : MAILINTVL;
1161 if (intvl < 1)
1162 intvl = 1;
1163 if (chktim + intvl > t)
1164 return;
1165 for (; *vp; vp++) {
1166 if (stat(short2str(*vp), &stb) < 0)
1167 continue;
1168 new = stb.st_mtime > time0.tv_sec;
1169 if (stb.st_size == 0 || stb.st_atime > stb.st_mtime ||
1170 (stb.st_atime < chktim && stb.st_mtime < chktim) ||
1171 (loginsh && !new))
1172 continue;
1173 if (cnt == 1)
1174 (void) fprintf(cshout, "You have %smail.\n", new ? "new " : "");
1175 else
1176 (void) fprintf(cshout, "%s in %s.\n", new ? "New mail" : "Mail",
1177 vis_str(*vp));
1178 }
1179 chktim = t;
1180 }
1181
1182 /*
1183 * Extract a home directory from the password file
1184 * The argument points to a buffer where the name of the
1185 * user whose home directory is sought is currently.
1186 * We write the home directory of the user back there.
1187 */
1188 int
1189 gethdir(home)
1190 Char *home;
1191 {
1192 Char *h;
1193 struct passwd *pw;
1194
1195 /*
1196 * Is it us?
1197 */
1198 if (*home == '\0') {
1199 if ((h = value(STRhome)) != NULL) {
1200 (void) Strcpy(home, h);
1201 return 0;
1202 }
1203 else
1204 return 1;
1205 }
1206
1207 if ((pw = getpwnam(short2str(home))) != NULL) {
1208 (void) Strcpy(home, str2short(pw->pw_dir));
1209 return 0;
1210 }
1211 else
1212 return 1;
1213 }
1214
1215 /*
1216 * When didfds is set, we do I/O from 0, 1, 2 otherwise from 15, 16, 17
1217 * We also check if the shell has already changed the decriptor to point to
1218 * 0, 1, 2 when didfds is set.
1219 */
1220 #define DESC(a) (*((int *) (a)) - (didfds && *((int *) a) >= FSHIN ? FSHIN : 0))
1221
1222 static int
1223 readf(oreo, buf, siz)
1224 void *oreo;
1225 char *buf;
1226 int siz;
1227 {
1228 return read(DESC(oreo), buf, siz);
1229 }
1230
1231
1232 static int
1233 writef(oreo, buf, siz)
1234 void *oreo;
1235 const char *buf;
1236 int siz;
1237 {
1238 return write(DESC(oreo), buf, siz);
1239 }
1240
1241 static fpos_t
1242 seekf(oreo, off, whence)
1243 void *oreo;
1244 fpos_t off;
1245 int whence;
1246 {
1247 return lseek(DESC(oreo), off, whence);
1248 }
1249
1250
1251 static int
1252 closef(oreo)
1253 void *oreo;
1254 {
1255 return close(DESC(oreo));
1256 }
1257
1258
1259 /*
1260 * Print the visible version of a string.
1261 */
1262 int
1263 vis_fputc(ch, fp)
1264 int ch;
1265 FILE *fp;
1266 {
1267 char uenc[5]; /* 4 + NULL */
1268
1269 if (ch & QUOTE)
1270 return fputc(ch & TRIM, fp);
1271 /*
1272 * XXX: When we are in AsciiOnly we want all characters >= 0200 to
1273 * be encoded, but currently there is no way in vis to do that.
1274 */
1275 (void) vis(uenc, ch & TRIM, VIS_NOSLASH, 0);
1276 return fputs(uenc, fp);
1277 }
1278
1279 /*
1280 * Move the initial descriptors to their eventual
1281 * resting places, closin all other units.
1282 */
1283 void
1284 initdesc()
1285 {
1286
1287 didfds = 0; /* 0, 1, 2 aren't set up */
1288 (void) ioctl(SHIN = dcopy(0, FSHIN), FIOCLEX, NULL);
1289 (void) ioctl(SHOUT = dcopy(1, FSHOUT), FIOCLEX, NULL);
1290 (void) ioctl(SHERR = dcopy(2, FSHERR), FIOCLEX, NULL);
1291 (void) ioctl(OLDSTD = dcopy(SHIN, FOLDSTD), FIOCLEX, NULL);
1292 closem();
1293 }
1294
1295
1296 void
1297 #ifdef PROF
1298 done(i)
1299 #else
1300 xexit(i)
1301 #endif
1302 int i;
1303 {
1304 untty();
1305 _exit(i);
1306 }
1307
1308 static Char **
1309 defaultpath()
1310 {
1311 char *ptr;
1312 Char **blk, **blkp;
1313 struct stat stb;
1314
1315 blkp = blk = (Char **) xmalloc((size_t) sizeof(Char *) * 10);
1316
1317 #define DIRAPPEND(a) \
1318 if (stat(ptr = a, &stb) == 0 && (stb.st_mode & S_IFMT) == S_IFDIR) \
1319 *blkp++ = SAVE(ptr)
1320
1321 DIRAPPEND(_PATH_BIN);
1322 DIRAPPEND(_PATH_USRBIN);
1323
1324 #undef DIRAPPEND
1325
1326 if (euid != 0 && uid != 0)
1327 *blkp++ = Strsave(STRdot);
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