home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / bsd_srcs / bin / csh / csh.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-02-05  |  30.0 KB  |  1,299 lines

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