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