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