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