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