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