csh.c revision 1.49 1 /* $NetBSD: csh.c,v 1.49 2020/01/12 18:36:55 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.49 2020/01/12 18:36:55 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 ssize_t readf(void *, void *, size_t);
97 static off_t seekf(void *, off_t, int);
98 static ssize_t writef(void *, const void *, size_t);
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
109 int
110 main(int argc, char *argv[])
111 {
112 struct sigaction oact;
113 Char *cp;
114 char *tcp, **tempv;
115 const char *ecp;
116 sigset_t nsigset;
117 int f;
118
119 cshin = stdin;
120 cshout = stdout;
121 csherr = stderr;
122
123 setprogname(argv[0]);
124 settimes(); /* Immed. estab. timing base */
125
126 /*
127 * Initialize non constant strings
128 */
129 #ifdef _PATH_BSHELL
130 STR_BSHELL = SAVE(_PATH_BSHELL);
131 #endif
132 #ifdef _PATH_CSHELL
133 STR_SHELLPATH = SAVE(_PATH_CSHELL);
134 #endif
135 STR_environ = blk2short(environ);
136 environ = short2blk(STR_environ); /* So that we can free it */
137 STR_WORD_CHARS = SAVE(WORD_CHARS);
138
139 HIST = '!';
140 HISTSUB = '^';
141 word_chars = STR_WORD_CHARS;
142
143 tempv = argv;
144 if (eq(str2short(tempv[0]), STRaout)) /* A.out's are quittable */
145 quitit = 1;
146 uid = getuid();
147 gid = getgid();
148 euid = geteuid();
149 egid = getegid();
150 /*
151 * We are a login shell if: 1. we were invoked as -<something> and we had
152 * no arguments 2. or we were invoked only with the -l flag
153 */
154 loginsh = (**tempv == '-' && argc == 1) ||
155 (argc == 2 && tempv[1][0] == '-' && tempv[1][1] == 'l' &&
156 tempv[1][2] == '\0');
157
158 if (loginsh && **tempv != '-') {
159 /*
160 * Mangle the argv space
161 */
162 tempv[1][0] = '\0';
163 tempv[1][1] = '\0';
164 tempv[1] = NULL;
165 for (tcp = *tempv; *tcp++;)
166 continue;
167 for (tcp--; tcp >= *tempv; tcp--)
168 tcp[1] = tcp[0];
169 *++tcp = '-';
170 argc--;
171 }
172 if (loginsh)
173 (void)time(&chktim);
174
175 AsciiOnly = 1;
176 #ifdef NLS
177 (void)setlocale(LC_ALL, "");
178 {
179 int k;
180
181 for (k = 0200; k <= 0377 && !Isprint(k); k++)
182 continue;
183 AsciiOnly = k > 0377;
184 }
185 #else
186 AsciiOnly = getenv("LANG") == NULL && getenv("LC_CTYPE") == NULL;
187 #endif /* NLS */
188
189 /*
190 * Move the descriptors to safe places. The variable didfds is 0 while we
191 * have only FSH* to work with. When didfds is true, we have 0,1,2 and
192 * prefer to use these.
193 */
194 initdesc();
195 /*
196 * XXX: This is to keep programs that use stdio happy.
197 * what we really want is freunopen() ....
198 * Closing cshin cshout and csherr (which are really stdin stdout
199 * and stderr at this point and then reopening them in the same order
200 * gives us again stdin == cshin stdout == cshout and stderr == csherr.
201 * If that was not the case builtins like printf that use stdio
202 * would break. But in any case we could fix that with memcpy and
203 * a bit of pointer manipulation...
204 * Fortunately this is not needed under the current implementation
205 * of stdio.
206 */
207 (void)fclose(cshin);
208 (void)fclose(cshout);
209 (void)fclose(csherr);
210 if (!(cshin = funopen2((void *) &SHIN, readf, writef, seekf, NULL,
211 closef)))
212 exit(1);
213 if (!(cshout = funopen2((void *) &SHOUT, readf, writef, seekf, NULL,
214 closef)))
215 exit(1);
216 if (!(csherr = funopen2((void *) &SHERR, readf, writef, seekf, NULL,
217 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 free(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 free doesn't care */
758 /* XXX yes it does */
759 for (i = 0; i < fblocks; i++)
760 free(fbuf[i]);
761 free(fbuf);
762
763 /* Reset input arena */
764 (void)memcpy(&B, &saveB, sizeof(B));
765
766 (void)close(SHIN), SHIN = oSHIN;
767 arginp = oarginp, onelflg = oonelflg;
768 evalp = oevalp, evalvec = oevalvec;
769 intty = oldintty, whyles = oldwhyl, gointr = ogointr;
770 if (enterhist)
771 HIST = OHIST;
772 enterhist = oenterhist;
773 cantell = otell;
774 }
775
776 resexit(oldexit);
777 /*
778 * If process reset() (effectively an unwind) then we must also unwind.
779 */
780 if (my_reenter)
781 stderror(ERR_SILENT);
782 insource = oinsource;
783 }
784
785 void
786 rechist(void)
787 {
788 Char buf[BUFSIZE], hbuf[BUFSIZE], *hfile;
789 int fp, ftmp, oldidfds;
790 struct varent *shist;
791
792 if (!fast) {
793 /*
794 * If $savehist is just set, we use the value of $history
795 * else we use the value in $savehist
796 */
797 if ((shist = adrof(STRsavehist)) != NULL) {
798 if (shist->vec[0][0] != '\0')
799 (void)Strcpy(hbuf, shist->vec[0]);
800 else if ((shist = adrof(STRhistory)) && shist->vec[0][0] != '\0')
801 (void)Strcpy(hbuf, shist->vec[0]);
802 else
803 return;
804 }
805 else
806 return;
807
808 if ((hfile = value(STRhistfile)) == STRNULL) {
809 hfile = Strcpy(buf, value(STRhome));
810 (void) Strcat(buf, STRsldthist);
811 }
812
813 if ((fp = open(short2str(hfile), O_WRONLY | O_CREAT | O_TRUNC,
814 0600)) == -1)
815 return;
816
817 oldidfds = didfds;
818 didfds = 0;
819 ftmp = SHOUT;
820 SHOUT = fp;
821 dumphist[2] = hbuf;
822 dohist(dumphist, NULL);
823 SHOUT = ftmp;
824 (void)close(fp);
825 didfds = oldidfds;
826 }
827 }
828
829 void
830 goodbye(void)
831 {
832 rechist();
833
834 if (loginsh) {
835 (void)signal(SIGQUIT, SIG_IGN);
836 (void)signal(SIGINT, SIG_IGN);
837 (void)signal(SIGTERM, SIG_IGN);
838 setintr = 0; /* No interrupts after "logout" */
839 if (!(adrof(STRlogout)))
840 set(STRlogout, STRnormal);
841 #ifdef _PATH_DOTLOGOUT
842 (void)srcfile(_PATH_DOTLOGOUT, 0, 0);
843 #endif
844 if (adrof(STRhome))
845 (void)srccat(value(STRhome), STRsldtlogout);
846 }
847 exitstat();
848 /* NOTREACHED */
849 }
850
851 __dead void
852 exitstat(void)
853 {
854 Char *s;
855 #ifdef PROF
856 monitor(0);
857 #endif
858 /*
859 * Note that if STATUS is corrupted (i.e. getn bombs) then error will exit
860 * directly because we poke child here. Otherwise we might continue
861 * unwarrantedly (sic).
862 */
863 child = 1;
864 s = value(STRstatus);
865 xexit(s ? getn(s) : 0);
866 /* NOTREACHED */
867 }
868
869 /*
870 * in the event of a HUP we want to save the history
871 */
872 static void
873 phup(int sig)
874 {
875 rechist();
876
877 /*
878 * We kill the last foreground process group. It then becomes
879 * responsible to propagate the SIGHUP to its progeny.
880 */
881 {
882 struct process *pp, *np;
883
884 for (pp = proclist.p_next; pp; pp = pp->p_next) {
885 np = pp;
886 /*
887 * Find if this job is in the foreground. It could be that
888 * the process leader has exited and the foreground flag
889 * is cleared for it.
890 */
891 do
892 /*
893 * If a process is in the foreground; we try to kill
894 * its process group. If we succeed, then the
895 * whole job is gone. Otherwise we keep going...
896 * But avoid sending HUP to the shell again.
897 */
898 if ((np->p_flags & PFOREGND) != 0 && np->p_jobid != shpgrp &&
899 kill(-np->p_jobid, SIGHUP) != -1) {
900 /* In case the job was suspended... */
901 (void)kill(-np->p_jobid, SIGCONT);
902 break;
903 }
904 while ((np = np->p_friends) != pp);
905 }
906 }
907 xexit(sig);
908 /* NOTREACHED */
909 }
910
911 Char *jobargv[2] = {STRjobs, 0};
912
913 /*
914 * Catch an interrupt, e.g. during lexical input.
915 * If we are an interactive shell, we reset the interrupt catch
916 * immediately. In any case we drain the shell output,
917 * and finally go through the normal error mechanism, which
918 * gets a chance to make the shell go away.
919 */
920 /* ARGSUSED */
921 void
922 pintr(int notused)
923 {
924 pintr1(1);
925 /* NOTREACHED */
926 }
927
928 void
929 pintr1(int wantnl)
930 {
931 Char **v;
932 sigset_t nsigset, osigset;
933
934 sigemptyset(&nsigset);
935 (void)sigprocmask(SIG_BLOCK, &nsigset, &osigset);
936 if (setintr) {
937 nsigset = osigset;
938 (void)sigdelset(&nsigset, SIGINT);
939 (void)sigprocmask(SIG_SETMASK, &nsigset, NULL);
940 if (pjobs) {
941 pjobs = 0;
942 (void)fprintf(cshout, "\n");
943 dojobs(jobargv, NULL);
944 stderror(ERR_NAME | ERR_INTR);
945 }
946 }
947 (void)sigdelset(&osigset, SIGCHLD);
948 (void)sigprocmask(SIG_SETMASK, &osigset, NULL);
949 (void)fpurge(cshout);
950 (void)endpwent();
951
952 /*
953 * If we have an active "onintr" then we search for the label. Note that if
954 * one does "onintr -" then we shan't be interruptible so we needn't worry
955 * about that here.
956 */
957 if (gointr) {
958 gotolab(gointr);
959 timflg = 0;
960 if ((v = pargv) != NULL)
961 pargv = 0, blkfree(v);
962 if ((v = gargv) != NULL)
963 gargv = 0, blkfree(v);
964 reset();
965 }
966 else if (intty && wantnl) {
967 (void)fputc('\r', cshout);
968 (void)fputc('\n', cshout);
969 }
970 stderror(ERR_SILENT);
971 /* NOTREACHED */
972 }
973
974 /*
975 * Process is the main driving routine for the shell.
976 * It runs all command processing, except for those within { ... }
977 * in expressions (which is run by a routine evalav in sh.exp.c which
978 * is a stripped down process), and `...` evaluation which is run
979 * also by a subset of this code in sh.glob.c in the routine backeval.
980 *
981 * The code here is a little strange because part of it is interruptible
982 * and hence freeing of structures appears to occur when none is necessary
983 * if this is ignored.
984 *
985 * Note that if catch is not set then we will unwind on any error.
986 * If an end-of-file occurs, we return.
987 */
988 static struct command *savet = NULL;
989
990 void
991 process(int catch)
992 {
993 struct command *t;
994 jmp_buf osetexit;
995 sigset_t nsigset;
996
997 t = savet;
998 savet = NULL;
999 getexit(osetexit);
1000 for (;;) {
1001 pendjob();
1002 paraml.next = paraml.prev = ¶ml;
1003 paraml.word = STRNULL;
1004 (void)setexit();
1005 justpr = enterhist; /* execute if not entering history */
1006
1007 /*
1008 * Interruptible during interactive reads
1009 */
1010 if (setintr) {
1011 sigemptyset(&nsigset);
1012 (void)sigaddset(&nsigset, SIGINT);
1013 (void)sigprocmask(SIG_UNBLOCK, &nsigset, NULL);
1014 }
1015
1016 /*
1017 * For the sake of reset()
1018 */
1019 freelex(¶ml);
1020 if (savet)
1021 freesyn(savet), savet = NULL;
1022
1023 if (haderr) {
1024 if (!catch) {
1025 /* unwind */
1026 doneinp = 0;
1027 resexit(osetexit);
1028 savet = t;
1029 reset();
1030 }
1031 haderr = 0;
1032 /*
1033 * Every error is eventually caught here or the shell dies. It is
1034 * at this point that we clean up any left-over open files, by
1035 * closing all but a fixed number of pre-defined files. Thus
1036 * routines don't have to worry about leaving files open due to
1037 * deeper errors... they will get closed here.
1038 */
1039 closem();
1040 continue;
1041 }
1042 if (doneinp) {
1043 doneinp = 0;
1044 break;
1045 }
1046 if (chkstop)
1047 chkstop--;
1048 if (neednote)
1049 pnote();
1050 if (intty && prompt && evalvec == 0) {
1051 mailchk();
1052 /*
1053 * If we are at the end of the input buffer then we are going to
1054 * read fresh stuff. Otherwise, we are rereading input and don't
1055 * need or want to prompt.
1056 */
1057 if (aret == F_SEEK && fseekp == feobp)
1058 printprompt();
1059 (void)fflush(cshout);
1060 }
1061 if (seterr) {
1062 free(seterr);
1063 seterr = NULL;
1064 }
1065
1066 /*
1067 * Echo not only on VERBOSE, but also with history expansion. If there
1068 * is a lexical error then we forego history echo.
1069 */
1070 if ((lex(¶ml) && !seterr && intty) || adrof(STRverbose)) {
1071 int odidfds = didfds;
1072 fflush(csherr);
1073 didfds = 0;
1074 prlex(csherr, ¶ml);
1075 fflush(csherr);
1076 didfds = odidfds;
1077 }
1078
1079 /*
1080 * The parser may lose space if interrupted.
1081 */
1082 if (setintr)
1083 (void)sigprocmask(SIG_BLOCK, &nsigset, NULL);
1084
1085 /*
1086 * Save input text on the history list if reading in old history, or it
1087 * is from the terminal at the top level and not in a loop.
1088 *
1089 * PWP: entry of items in the history list while in a while loop is done
1090 * elsewhere...
1091 */
1092 if (enterhist || (catch && intty && !whyles))
1093 savehist(¶ml);
1094
1095 /*
1096 * Print lexical error messages, except when sourcing history lists.
1097 */
1098 if (!enterhist && seterr)
1099 stderror(ERR_OLD);
1100
1101 /*
1102 * If had a history command :p modifier then this is as far as we
1103 * should go
1104 */
1105 if (justpr)
1106 reset();
1107
1108 alias(¶ml);
1109
1110 /*
1111 * Parse the words of the input into a parse tree.
1112 */
1113 savet = syntax(paraml.next, ¶ml, 0);
1114 if (seterr)
1115 stderror(ERR_OLD);
1116
1117 execute(savet, (tpgrp > 0 ? tpgrp : -1), NULL, NULL);
1118
1119 /*
1120 * Made it!
1121 */
1122 freelex(¶ml);
1123 freesyn((struct command *) savet), savet = NULL;
1124 }
1125 resexit(osetexit);
1126 savet = t;
1127 }
1128
1129 void
1130 /*ARGSUSED*/
1131 dosource(Char **v, struct command *t)
1132 {
1133 Char buf[BUFSIZE], *f;
1134 int hflg;
1135
1136 hflg = 0;
1137 v++;
1138 if (*v && eq(*v, STRmh)) {
1139 if (*++v == NULL)
1140 stderror(ERR_NAME | ERR_HFLAG);
1141 hflg++;
1142 }
1143 (void)Strcpy(buf, *v);
1144 f = globone(buf, G_ERROR);
1145 (void)strcpy((char *)buf, short2str(f));
1146 free(f);
1147 if (!srcfile((char *)buf, 0, hflg) && !hflg)
1148 stderror(ERR_SYSTEM, (char *)buf, strerror(errno));
1149 }
1150
1151 /*
1152 * Check for mail.
1153 * If we are a login shell, then we don't want to tell
1154 * about any mail file unless its been modified
1155 * after the time we started.
1156 * This prevents us from telling the user things he already
1157 * knows, since the login program insists on saying
1158 * "You have mail."
1159 */
1160 static void
1161 mailchk(void)
1162 {
1163 struct stat stb;
1164 struct varent *v;
1165 Char **vp;
1166 time_t t;
1167 int cnt, intvl;
1168 int new;
1169
1170 v = adrof(STRmail);
1171 if (v == 0)
1172 return;
1173 (void)time(&t);
1174 vp = v->vec;
1175 cnt = blklen(vp);
1176 intvl = (cnt && number(*vp)) ? (--cnt, getn(*vp++)) : MAILINTVL;
1177 if (intvl < 1)
1178 intvl = 1;
1179 if (chktim + intvl > t)
1180 return;
1181 for (; *vp; vp++) {
1182 if (stat(short2str(*vp), &stb) < 0)
1183 continue;
1184 new = stb.st_mtime > time0.tv_sec;
1185 if (stb.st_size == 0 || stb.st_atime > stb.st_mtime ||
1186 (stb.st_atime < chktim && stb.st_mtime < chktim) ||
1187 (loginsh && !new))
1188 continue;
1189 if (cnt == 1)
1190 (void)fprintf(cshout, "You have %smail.\n", new ? "new " : "");
1191 else
1192 (void)fprintf(cshout, "%s in %s.\n", new ? "New mail" : "Mail",
1193 vis_str(*vp));
1194 }
1195 chktim = t;
1196 }
1197
1198 /*
1199 * Extract a home directory from the password file
1200 * The argument points to a buffer where the name of the
1201 * user whose home directory is sought is currently.
1202 * We write the home directory of the user back there.
1203 */
1204 int
1205 gethdir(Char *home)
1206 {
1207 struct passwd *pw;
1208 Char *h;
1209
1210 /*
1211 * Is it us?
1212 */
1213 if (*home == '\0') {
1214 if ((h = value(STRhome)) != NULL) {
1215 (void)Strcpy(home, h);
1216 return 0;
1217 }
1218 else
1219 return 1;
1220 }
1221
1222 if ((pw = getpwnam(short2str(home))) != NULL) {
1223 (void)Strcpy(home, str2short(pw->pw_dir));
1224 return 0;
1225 }
1226 else
1227 return 1;
1228 }
1229
1230 /*
1231 * When didfds is set, we do I/O from 0, 1, 2 otherwise from 15, 16, 17
1232 * We also check if the shell has already changed the descriptor to point to
1233 * 0, 1, 2 when didfds is set.
1234 */
1235 #define DESC(a) (*((int *) (a)) - (didfds && *((int *) a) >= FSHIN ? FSHIN : 0))
1236
1237 static ssize_t
1238 readf(void *oreo, void *buf, size_t siz)
1239 {
1240 return read(DESC(oreo), buf, siz);
1241 }
1242
1243
1244 static ssize_t
1245 writef(void *oreo, const void *buf, size_t siz)
1246 {
1247 return write(DESC(oreo), buf, siz);
1248 }
1249
1250 static off_t
1251 seekf(void *oreo, off_t off, int whence)
1252 {
1253 return lseek(DESC(oreo), off, whence);
1254 }
1255
1256
1257 static int
1258 closef(void *oreo)
1259 {
1260 return close(DESC(oreo));
1261 }
1262
1263
1264 /*
1265 * Print the visible version of a string.
1266 */
1267 int
1268 vis_fputc(int ch, FILE *fp)
1269 {
1270 char uenc[5]; /* 4 + NULL */
1271
1272 if (ch & QUOTE)
1273 return fputc(ch & TRIM, fp);
1274 /*
1275 * XXX: When we are in AsciiOnly we want all characters >= 0200 to
1276 * be encoded, but currently there is no way in vis to do that.
1277 */
1278 (void)vis(uenc, ch & TRIM, VIS_NOSLASH, 0);
1279 return (fputs(uenc, fp));
1280 }
1281
1282 /*
1283 * Move the initial descriptors to their eventual
1284 * resting places, closing all other units.
1285 */
1286 void
1287 initdesc(void)
1288 {
1289 didfds = 0; /* 0, 1, 2 aren't set up */
1290 (void)ioctl(SHIN = dcopy(0, FSHIN), FIOCLEX, NULL);
1291 (void)ioctl(SHOUT = dcopy(1, FSHOUT), FIOCLEX, NULL);
1292 (void)ioctl(SHERR = dcopy(2, FSHERR), FIOCLEX, NULL);
1293 (void)ioctl(OLDSTD = dcopy(SHIN, FOLDSTD), FIOCLEX, NULL);
1294 closem();
1295 }
1296
1297
1298 __dead void
1299 #ifdef PROF
1300 done(int i)
1301 #else
1302 xexit(int i)
1303 #endif
1304 {
1305 untty();
1306 _exit(i);
1307 /* NOTREACHED */
1308 }
1309
1310 #ifndef _PATH_DEFPATH
1311 static Char **
1312 defaultpath(void)
1313 {
1314 struct stat stb;
1315 Char **blk, **blkp;
1316 char *ptr;
1317
1318 blkp = blk = xmalloc((size_t) sizeof(Char *) * 10);
1319
1320 #define DIRAPPEND(a) \
1321 if (stat(ptr = a, &stb) == 0 && S_ISDIR(stb.st_mode)) \
1322 *blkp++ = SAVE(ptr)
1323 #ifdef RESCUEDIR
1324 DIRAPPEND(RESCUEDIR);
1325 #endif
1326 DIRAPPEND(_PATH_BIN);
1327 DIRAPPEND(_PATH_USRBIN);
1328
1329 #undef DIRAPPEND
1330
1331 #if 0
1332 if (euid != 0 && uid != 0)
1333 *blkp++ = Strsave(STRdot);
1334 #endif
1335
1336 *blkp = NULL;
1337 return (blk);
1338 }
1339 #endif /* _PATH_DEFPATH */
1340
1341 void
1342 printprompt(void)
1343 {
1344 Char *cp;
1345
1346 if (editing)
1347 return;
1348
1349 if (!whyles) {
1350 for (cp = value(STRprompt); *cp; cp++)
1351 if (*cp == HIST)
1352 (void)fprintf(cshout, "%d", eventno + 1);
1353 else {
1354 if (*cp == '\\' && cp[1] == HIST)
1355 cp++;
1356 (void)vis_fputc(*cp | QUOTE, cshout);
1357 }
1358 }
1359 else
1360 /*
1361 * Prompt for forward reading loop body content.
1362 */
1363 (void)fprintf(cshout, "? ");
1364 (void)fflush(cshout);
1365 }
1366
1367 #ifdef EDIT
1368 char *
1369 printpromptstr(EditLine *elx) {
1370 static char pbuf[1024];
1371 static char qspace[] = "? ";
1372 Char *cp;
1373 size_t i;
1374
1375 if (whyles)
1376 return qspace;
1377
1378 i = 0;
1379 for (cp = value(STRprompt); *cp; cp++) {
1380 if (i >= sizeof(pbuf))
1381 break;
1382 if (*cp == HIST) {
1383 int r;
1384 r = snprintf(pbuf + i, sizeof(pbuf) - i, "%d", eventno + 1);
1385 if (r > 0)
1386 i += (size_t)r;
1387 } else
1388 pbuf[i++] = (char)*cp;
1389 }
1390 if (i >= sizeof(pbuf))
1391 i = sizeof(pbuf) - 1;
1392 pbuf[i] = '\0';
1393 return pbuf;
1394 }
1395 #endif
1396