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