]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/tcsh/sh.c
This commit was generated by cvs2svn to compensate for changes in r133931,
[FreeBSD/FreeBSD.git] / contrib / tcsh / sh.c
1 /* $Header: /src/pub/tcsh/sh.c,v 3.109 2004/02/21 20:34:24 christos Exp $ */
2 /*
3  * sh.c: Main shell routines
4  */
5 /*-
6  * Copyright (c) 1980, 1991 The Regents of the University of California.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. 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 #define EXTERN  /* Intern */
34 #include "sh.h"
35
36 #ifndef lint
37 char    copyright[] =
38 "@(#) Copyright (c) 1991 The Regents of the University of California.\n\
39  All rights reserved.\n";
40 #endif /* not lint */
41
42 RCSID("$Id: sh.c,v 3.109 2004/02/21 20:34:24 christos Exp $")
43
44 #include "tc.h"
45 #include "ed.h"
46 #include "tw.h"
47
48 extern bool MapsAreInited;
49 extern bool NLSMapsAreInited;
50 extern bool NoNLSRebind;
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  * Filename recognition added:
62  * Ken Greer, Ind. Consultant, Palo Alto CA
63  * October 1983.
64  *
65  * Karl Kleinpaste, Computer Consoles, Inc.
66  * Added precmd, periodic/tperiod, prompt changes,
67  * directory stack hack, and login watch.
68  * Sometime March 1983 - Feb 1984.
69  *
70  * Added scheduled commands, including the "sched" command,
71  * plus the call to sched_run near the precmd et al
72  * routines.
73  * Upgraded scheduled events for running events while
74  * sitting idle at command input.
75  *
76  * Paul Placeway, Ohio State
77  * added stuff for running with twenex/inputl  9 Oct 1984.
78  *
79  * ported to Apple Unix (TM) (OREO)  26 -- 29 Jun 1987
80  */
81
82 jmp_buf_t reslab INIT_ZERO_STRUCT;
83
84 static const char tcshstr[] = "tcsh";
85 #ifdef WINNT_NATIVE
86 static const char tcshstr_nt[] = "tcsh.exe";
87 #endif /* WINNT_NATIVE */
88
89 signalfun_t parintr = 0;        /* Parents interrupt catch */
90 signalfun_t parterm = 0;        /* Parents terminate catch */
91
92 #ifdef TESLA
93 int do_logout = 0;
94 #endif /* TESLA */
95
96
97 bool    use_fork = 0;           /* use fork() instead of vfork()? */
98
99 /*
100  * Magic pointer values. Used to specify other invalid conditions aside
101  * from null.
102  */
103 static Char     INVCHAR;
104 Char    *INVPTR = &INVCHAR;
105 Char    **INVPPTR = &INVPTR;
106
107 static int     nofile = 0;
108 static bool    reenter = 0;
109 static bool    nverbose = 0;
110 static bool    nexececho = 0;
111 static bool    quitit = 0;
112 static bool    rdirs = 0;
113 bool    fast = 0;
114 static bool    batch = 0;
115 static bool    mflag = 0;
116 static bool    prompt = 1;
117 static int     enterhist = 0;
118 bool    tellwhat = 0;
119 time_t  t_period;
120 Char  *ffile = NULL;
121 bool    dolzero = 0;
122 int     insource = 0;
123 int     exitset = 0;
124 static time_t  chktim;          /* Time mail last checked */
125 char *progname;
126 int tcsh;
127 extern char **environ;
128
129 /*
130  * This preserves the input state of the shell. It is used by
131  * st_save and st_restore to manupulate shell state.
132  */
133 struct saved_state {
134     int           insource;
135     int           OLDSTD;
136     int           SHIN;
137     int           SHOUT;
138     int           SHDIAG;
139     int           intty;
140     struct whyle *whyles;
141     Char         *gointr;
142     Char         *arginp;
143     Char         *evalp;
144     Char        **evalvec;
145     Char         *alvecp;
146     Char        **alvec;
147     int           onelflg;
148     bool          enterhist;
149     Char        **argv;
150     Char          HIST;
151     bool          cantell;
152     struct Bin    B;
153     /* These keep signal state and setjump state */
154 #ifdef BSDSIGS
155     sigmask_t     mask;
156 #endif
157     jmp_buf_t     oldexit;
158     int           reenter;
159 };
160
161 static  int               srccat        __P((Char *, Char *));
162 #ifndef WINNT_NATIVE
163 static  int               srcfile       __P((char *, bool, int, Char **));
164 #else
165 int               srcfile       __P((char *, bool, int, Char **));
166 #endif /*WINNT_NATIVE*/
167 static  sigret_t          phup          __P((int));
168 static  void              srcunit       __P((int, bool, int, Char **));
169 static  void              mailchk       __P((void));
170 #ifndef _PATH_DEFPATH
171 static  Char            **defaultpath   __P((void));
172 #endif
173 static  void              record        __P((void));
174 static  void              st_save       __P((struct saved_state *, int, int,
175                                              Char **, Char **));
176 static  void              st_restore    __P((struct saved_state *, Char **));
177
178         int               main          __P((int, char **));
179
180 int
181 main(argc, argv)
182     int     argc;
183     char  **argv;
184 {
185     register Char *cp;
186 #ifdef AUTOLOGOUT
187     register Char *cp2;
188 #endif
189     register char *tcp, *ttyn;
190     register int f;
191     register char **tempv;
192     int osetintr;
193     signalfun_t oparintr;
194
195 #ifdef BSDSIGS
196     sigvec_t osv;
197 #endif /* BSDSIGS */
198
199 #ifdef WINNT_NATIVE
200     nt_init();
201 #endif /* WINNT_NATIVE */
202 #if defined(NLS_CATALOGS) && defined(LC_MESSAGES)
203     (void) setlocale(LC_MESSAGES, "");
204 #endif /* NLS_CATALOGS && LC_MESSAGES */
205
206 #ifdef NLS
207 # ifdef LC_CTYPE
208     (void) setlocale(LC_CTYPE, ""); /* for iscntrl */
209 # endif /* LC_CTYPE */
210 #endif /* NLS */
211
212     nlsinit();
213
214 #ifdef MALLOC_TRACE
215      mal_setstatsfile(fdopen(dup2(open("/tmp/tcsh.trace", 
216                                        O_WRONLY|O_CREAT|O_LARGEFILE, 0666), 25),
217                                        "w"));
218      mal_trace(1);
219 #endif /* MALLOC_TRACE */
220
221 #if !(defined(BSDTIMES) || defined(_SEQUENT_)) && defined(POSIX)
222 # ifdef _SC_CLK_TCK
223     clk_tck = (clock_t) sysconf(_SC_CLK_TCK);
224 # else /* ! _SC_CLK_TCK */
225 #  ifdef CLK_TCK
226     clk_tck = CLK_TCK;
227 #  else /* !CLK_TCK */
228     clk_tck = HZ;
229 #  endif /* CLK_TCK */
230 # endif /* _SC_CLK_TCK */
231 #endif /* !BSDTIMES && POSIX */
232
233     settimes();                 /* Immed. estab. timing base */
234 #ifdef TESLA
235     do_logout = 0;
236 #endif /* TESLA */
237
238     /*
239      * Make sure we have 0, 1, 2 open
240      * Otherwise `` jobs will not work... (From knaff@poly.polytechnique.fr)
241      */
242     {
243         do 
244             if ((f = open(_PATH_DEVNULL, O_RDONLY|O_LARGEFILE)) == -1 &&
245                 (f = open("/", O_RDONLY|O_LARGEFILE)) == -1) 
246                 exit(1);
247         while (f < 3);
248         (void) close(f);
249     }
250
251 #ifdef O_TEXT
252     setmode(0, O_TEXT);
253 #endif
254
255     osinit();                   /* Os dependent initialization */
256
257     
258     {
259         char *t;
260
261         t = strrchr(argv[0], '/');
262 #ifdef WINNT_NATIVE
263         {
264             char *s = strrchr(argv[0], '\\');
265             if (s)
266                 t = s;
267         }
268 #endif /* WINNT_NATIVE */
269         t = t ? t + 1 : argv[0];
270         if (*t == '-') t++;
271         progname = strsave((t && *t) ? t : tcshstr);    /* never want a null */
272         tcsh = strcmp(progname, tcshstr) == 0;
273     }
274
275     /*
276      * Initialize non constant strings
277      */
278 #ifdef _PATH_BSHELL
279     STR_BSHELL = SAVE(_PATH_BSHELL);
280 #endif
281 #ifdef _PATH_TCSHELL
282     STR_SHELLPATH = SAVE(_PATH_TCSHELL);
283 #else
284 # ifdef _PATH_CSHELL
285     STR_SHELLPATH = SAVE(_PATH_CSHELL);
286 # endif
287 #endif
288     STR_environ = blk2short(environ);
289     environ = short2blk(STR_environ);   /* So that we can free it */
290     STR_WORD_CHARS = SAVE(WORD_CHARS);
291
292     HIST = '!';
293     HISTSUB = '^';
294     PRCH = '>';
295     PRCHROOT = '#';
296     word_chars = STR_WORD_CHARS;
297     bslash_quote = 0;           /* PWP: do tcsh-style backslash quoting? */
298
299     /* Default history size to 100 */
300     set(STRhistory, SAVE("100"), VAR_READWRITE);
301
302     tempv = argv;
303     ffile = SAVE(tempv[0]);
304     dolzero = 0;
305     if (eq(ffile, STRaout))     /* A.out's are quittable */
306         quitit = 1;
307     uid = getuid();
308     gid = getgid();
309     euid = geteuid();
310     egid = getegid();
311     /*
312      * We are a login shell if: 1. we were invoked as -<something> with
313      * optional arguments 2. or we were invoked only with the -l flag
314      */
315     loginsh = (**tempv == '-') || (argc == 2 &&
316                                    tempv[1][0] == '-' && tempv[1][1] == 'l' &&
317                                                 tempv[1][2] == '\0');
318 #ifdef _VMS_POSIX
319     /* No better way to find if we are a login shell */
320     if (!loginsh) {
321         loginsh = (argc == 1 && getppid() == 1);
322         **tempv = '-';  /* Avoid giving VMS an acidic stomach */
323     }
324 #endif /* _VMS_POSIX */
325
326     if (loginsh && **tempv != '-') {
327         /*
328          * Mangle the argv space
329          */
330         tempv[1][0] = '\0';
331         tempv[1][1] = '\0';
332         tempv[1] = NULL;
333         for (tcp = *tempv; *tcp++;)
334              continue;
335         for (tcp--; tcp >= *tempv; tcp--)
336             tcp[1] = tcp[0];
337         *++tcp = '-';
338         argc--;
339     }
340     if (loginsh) {
341         (void) time(&chktim);
342         set(STRloginsh, Strsave(STRNULL), VAR_READWRITE);
343     }
344
345     AsciiOnly = 1;
346     NoNLSRebind = getenv("NOREBIND") != NULL;
347 #ifdef NLS
348 # ifdef SETLOCALEBUG
349     dont_free = 1;
350 # endif /* SETLOCALEBUG */
351     (void) setlocale(LC_ALL, "");
352 # ifdef LC_COLLATE
353     (void) setlocale(LC_COLLATE, "");
354 # endif
355 # ifdef SETLOCALEBUG
356     dont_free = 0;
357 # endif /* SETLOCALEBUG */
358 # ifdef STRCOLLBUG
359     fix_strcoll_bug();
360 # endif /* STRCOLLBUG */
361
362     {
363         int     k;
364
365         for (k = 0200; k <= 0377 && !Isprint(k); k++)
366             continue;
367         AsciiOnly = k > 0377;
368     }
369 #else
370     AsciiOnly = getenv("LANG") == NULL && getenv("LC_CTYPE") == NULL;
371 #endif                          /* NLS */
372     if (MapsAreInited && !NLSMapsAreInited)
373         ed_InitNLSMaps();
374     ResetArrowKeys();
375
376     /*
377      * Initialize for periodic command intervals. Also, initialize the dummy
378      * tty list for login-watch.
379      */
380     (void) time(&t_period);
381 #ifndef HAVENOUTMP
382     initwatch();
383 #endif /* !HAVENOUTMP */
384
385 #if defined(alliant)
386     /*
387      * From:  Jim Pace <jdp@research.att.com>
388      * tcsh does not work properly on the alliants through an rlogin session.
389      * The shell generally hangs.  Also, reference to the controlling terminal
390      * does not work ( ie: echo foo > /dev/tty ).
391      *
392      * A security feature was added to rlogind affecting FX/80's Concentrix
393      * from revision 5.5.xx upwards (through 5.7 where this fix was implemented)
394      * This security change also affects the FX/2800 series.
395      * The security change to rlogind requires the process group of an rlogin
396      * session become disassociated with the tty in rlogind.
397      *
398      * The changes needed are:
399      * 1. set the process group
400      * 2. reenable the control terminal
401      */
402      if (loginsh && isatty(SHIN)) {
403          ttyn = (char *) ttyname(SHIN);
404          (void) close(SHIN);
405          SHIN = open(ttyn, O_RDWR|O_LARGEFILE);
406          shpgrp = getpid();
407          (void) ioctl (SHIN, TIOCSPGRP, (ioctl_t) &shpgrp);
408          (void) setpgid(0, shpgrp);
409      }
410 #endif /* alliant */
411
412     /*
413      * Move the descriptors to safe places. The variable didfds is 0 while we
414      * have only FSH* to work with. When didfds is true, we have 0,1,2 and
415      * prefer to use these.
416      */
417     initdesc();
418
419     /*
420      * Get and set the tty now
421      */
422     if ((ttyn = ttyname(SHIN)) != NULL) {
423         /*
424          * Could use rindex to get rid of other possible path components, but
425          * hpux preserves the subdirectory /pty/ when storing the tty name in
426          * utmp, so we keep it too.
427          */
428         if (strncmp(ttyn, "/dev/", 5) == 0)
429             set(STRtty, cp = SAVE(ttyn + 5), VAR_READWRITE);
430         else
431             set(STRtty, cp = SAVE(ttyn), VAR_READWRITE);
432     }
433     else
434         set(STRtty, cp = SAVE(""), VAR_READWRITE);
435     /*
436      * Initialize the shell variables. ARGV and PROMPT are initialized later.
437      * STATUS is also munged in several places. CHILD is munged when
438      * forking/waiting
439      */
440
441     /*
442      * 7-10-87 Paul Placeway autologout should be set ONLY on login shells and
443      * on shells running as root.  Out of these, autologout should NOT be set
444      * for any psudo-terminals (this catches most window systems) and not for
445      * any terminal running X windows.
446      * 
447      * At Ohio State, we have had problems with a user having his X session 
448      * drop out from under him (on a Sun) because the shell in his master 
449      * xterm timed out and exited.
450      * 
451      * Really, this should be done with a program external to the shell, that
452      * watches for no activity (and NO running programs, such as dump) on a
453      * terminal for a long peroid of time, and then SIGHUPS the shell on that
454      * terminal.
455      * 
456      * bugfix by Rich Salz <rsalz@PINEAPPLE.BBN.COM>: For root rsh things 
457      * allways first check to see if loginsh or really root, then do things 
458      * with ttyname()
459      * 
460      * Also by Jean-Francois Lamy <lamy%ai.toronto.edu@RELAY.CS.NET>: check the
461      * value of cp before using it! ("root can rsh too")
462      * 
463      * PWP: keep the nested ifs; the order of the tests matters and a good 
464      * (smart) C compiler might re-arange things wrong.
465      */
466 #ifdef AUTOLOGOUT
467 # ifdef convex
468     if (uid == 0) {
469         /*  root always has a 15 minute autologout  */
470         set(STRautologout, Strsave(STRrootdefautologout), VAR_READWRITE);
471     }
472     else
473         if (loginsh)
474             /*  users get autologout set to 0  */
475             set(STRautologout, Strsave(STR0), VAR_READWRITE);
476 # else /* convex */
477     if (loginsh || (uid == 0)) {
478         if (*cp) {
479             /* only for login shells or root and we must have a tty */
480             if ((cp2 = Strrchr(cp, (Char) '/')) != NULL) {
481                 cp = cp2 + 1;
482             }
483             else
484                 cp2 = cp;
485             if (!(((Strncmp(cp2, STRtty, 3) == 0) && Isalpha(cp2[3])) ||
486                   ((Strncmp(cp, STRpts, 3) == 0) && cp[3] == '/'))) {
487                 if (getenv("DISPLAY") == NULL) {
488                     /* NOT on X window shells */
489                     set(STRautologout, Strsave(STRdefautologout), 
490                         VAR_READWRITE);
491                 }
492             }
493         }
494     }
495 # endif /* convex */
496 #endif /* AUTOLOGOUT */
497
498     (void) sigset(SIGALRM, alrmcatch);
499
500     set(STRstatus, Strsave(STR0), VAR_READWRITE);
501
502     /*
503      * get and set machine specific environment variables
504      */
505     getmachine();
506
507
508     /*
509      * Publish the selected echo style
510      */
511 #if ECHO_STYLE != BSD_ECHO
512     if (tcsh) {
513 # if ECHO_STYLE == NONE_ECHO
514         set(STRecho_style, Strsave(STRnone), VAR_READWRITE);
515 # endif /* ECHO_STYLE == NONE_ECHO */
516 # if ECHO_STYLE == SYSV_ECHO
517         set(STRecho_style, Strsave(STRsysv), VAR_READWRITE);
518 # endif /* ECHO_STYLE == SYSV_ECHO */
519 # if ECHO_STYLE == BOTH_ECHO
520         set(STRecho_style, Strsave(STRboth), VAR_READWRITE);
521 # endif /* ECHO_STYLE == BOTH_ECHO */
522     } else
523 #endif /* ECHO_STYLE != BSD_ECHO */
524         set(STRecho_style, Strsave(STRbsd), VAR_READWRITE);
525
526     /*
527      * increment the shell level.
528      */
529     shlvl(1);
530
531     if ((tcp = getenv("HOME")) != NULL) {
532         if (strlen(tcp) >= MAXPATHLEN) {
533             struct passwd *pw;
534             if ((pw = getpwuid(getuid())) != NULL)
535                 cp = quote(SAVE(pw->pw_dir));
536             else {
537                 tcp[MAXPATHLEN-1] = '\0';
538                 cp = quote(SAVE(tcp));
539             }
540         } else {
541             cp = quote(SAVE(tcp));
542         }
543     } else
544         cp = NULL;
545
546     if (cp == NULL)
547         fast = 1;               /* No home -> can't read scripts */
548     else
549         set(STRhome, cp, VAR_READWRITE);
550
551     dinit(cp);                  /* dinit thinks that HOME == cwd in a login
552                                  * shell */
553     /*
554      * Grab other useful things from the environment. Should we grab
555      * everything??
556      */
557     {
558         char *cln, *cus, *cgr;
559         Char    buff[BUFSIZE];
560         struct passwd *pw;
561         struct group *gr;
562
563
564 #ifdef apollo
565         int     oid = getoid();
566
567         (void) Itoa(oid, buff, 0, 0);
568         set(STRoid, Strsave(buff), VAR_READWRITE);
569 #endif /* apollo */
570
571         (void) Itoa(uid, buff, 0, 0);
572         set(STRuid, Strsave(buff), VAR_READWRITE);
573
574         (void) Itoa(gid, buff, 0, 0);
575         set(STRgid, Strsave(buff), VAR_READWRITE);
576
577         cln = getenv("LOGNAME");
578         cus = getenv("USER");
579         if (cus != NULL)
580             set(STRuser, quote(SAVE(cus)), VAR_READWRITE);
581         else if (cln != NULL)
582             set(STRuser, quote(SAVE(cln)), VAR_READWRITE);
583         else if ((pw = getpwuid(uid)) == NULL)
584             set(STRuser, SAVE("unknown"), VAR_READWRITE);
585         else
586             set(STRuser, SAVE(pw->pw_name), VAR_READWRITE);
587         if (cln == NULL)
588             tsetenv(STRLOGNAME, varval(STRuser));
589         if (cus == NULL)
590             tsetenv(STRKUSER, varval(STRuser));
591         
592         cgr = getenv("GROUP");
593         if (cgr != NULL)
594             set(STRgroup, quote(SAVE(cgr)), VAR_READWRITE);
595         else if ((gr = getgrgid(gid)) == NULL)
596             set(STRgroup, SAVE("unknown"), VAR_READWRITE);
597         else
598             set(STRgroup, SAVE(gr->gr_name), VAR_READWRITE);
599         if (cgr == NULL)
600             tsetenv(STRKGROUP, varval(STRgroup));
601     }
602
603     /*
604      * HOST may be wrong, since rexd transports the entire environment on sun
605      * 3.x Just set it again
606      */
607     {
608         char    cbuff[MAXHOSTNAMELEN];
609
610         if (gethostname(cbuff, sizeof(cbuff)) >= 0) {
611             cbuff[sizeof(cbuff) - 1] = '\0';    /* just in case */
612             tsetenv(STRHOST, str2short(cbuff));
613         }
614         else
615             tsetenv(STRHOST, str2short("unknown"));
616     }
617
618
619 #ifdef REMOTEHOST
620     /*
621      * Try to determine the remote host we were logged in from.
622      */
623     remotehost();
624 #endif /* REMOTEHOST */
625  
626 #ifdef apollo
627     if ((tcp = getenv("SYSTYPE")) == NULL)
628         tcp = "bsd4.3";
629     tsetenv(STRSYSTYPE, quote(str2short(tcp)));
630 #endif /* apollo */
631
632     /*
633      * set editing on by default, unless running under Emacs as an inferior
634      * shell.
635      * We try to do this intelligently. If $TERM is available, then it
636      * should determine if we should edit or not. $TERM is preserved
637      * across rlogin sessions, so we will not get confused if we rlogin
638      * under an emacs shell. Another advantage is that if we run an
639      * xterm under an emacs shell, then the $TERM will be set to 
640      * xterm, so we are going to want to edit. Unfortunately emacs
641      * does not restore all the tty modes, so xterm is not very well
642      * set up. But this is not the shell's fault.
643      * Also don't edit if $TERM == wm, for when we're running under an ATK app.
644      * Finally, emacs compiled under terminfo, sets the terminal to dumb,
645      * so disable editing for that too.
646      * 
647      * Unfortunately, in some cases the initial $TERM setting is "unknown",
648      * "dumb", or "network" which is then changed in the user's startup files.
649      * We fix this by setting noediting here if $TERM is unknown/dumb and
650      * if noediting is set, we switch on editing if $TERM is changed.
651      */
652     if ((tcp = getenv("TERM")) != NULL) {
653         set(STRterm, quote(SAVE(tcp)), VAR_READWRITE);
654         noediting = strcmp(tcp, "unknown") == 0 || strcmp(tcp, "dumb") == 0 ||
655                     strcmp(tcp, "network") == 0;
656         editing = strcmp(tcp, "emacs") != 0 && strcmp(tcp, "wm") != 0 &&
657                   !noediting;
658     }
659     else {
660         noediting = 0;
661         editing = ((tcp = getenv("EMACS")) == NULL || strcmp(tcp, "t") != 0);
662     }
663
664     /* 
665      * The 'edit' variable is either set or unset.  It doesn't 
666      * need a value.  Making it 'emacs' might be confusing. 
667      */
668     if (editing)
669         set(STRedit, Strsave(STRNULL), VAR_READWRITE);
670
671
672     /*
673      * still more mutability: make the complete routine automatically add the
674      * suffix of file names...
675      */
676     set(STRaddsuffix, Strsave(STRNULL), VAR_READWRITE);
677
678     /*
679      * Random default kill ring size
680      */
681     set(STRkillring, SAVE("30"), VAR_READWRITE);
682
683     /*
684      * Re-initialize path if set in environment
685      */
686     if ((tcp = getenv("PATH")) == NULL)
687 #ifdef _PATH_DEFPATH
688         importpath(str2short(_PATH_DEFPATH));
689 #else /* !_PATH_DEFPATH */
690         setq(STRpath, defaultpath(), &shvhed, VAR_READWRITE);
691 #endif /* _PATH_DEFPATH */
692     else
693         /* Importpath() allocates memory for the path, and the
694          * returned pointer from SAVE() was discarded, so
695          * this was a memory leak.. (sg)
696          *
697          * importpath(SAVE(tcp));
698          */
699         importpath(str2short(tcp));
700
701
702     {
703         /* If the SHELL environment variable ends with "tcsh", set
704          * STRshell to the same path.  This is to facilitate using
705          * the executable in environments where the compiled-in
706          * default isn't appropriate (sg).
707          */
708
709         int sh_len = 0;
710
711         if ((tcp = getenv("SHELL")) != NULL) {
712             sh_len = strlen(tcp);
713             if ((sh_len >= 5 && strcmp(tcp + (sh_len - 5), "/tcsh") == 0) || 
714                 (!tcsh && sh_len >= 4 && strcmp(tcp + (sh_len - 4), "/csh") == 0))
715                 set(STRshell, quote(SAVE(tcp)), VAR_READWRITE);
716             else
717                 sh_len = 0;
718         }
719         if (sh_len == 0)
720             set(STRshell, Strsave(STR_SHELLPATH), VAR_READWRITE);
721     }
722
723 #ifdef COLOR_LS_F
724     if ((tcp = getenv("LS_COLORS")) != NULL)
725         parseLS_COLORS(str2short(tcp));
726 #endif /* COLOR_LS_F */
727
728     doldol = putn((int) getpid());      /* For $$ */
729 #ifdef WINNT_NATIVE
730     {
731         char *strtmp1, strtmp2[MAXPATHLEN];
732         if ((strtmp1 = getenv("TMP")) != NULL)
733             wsprintf(strtmp2, "%s/%s", strtmp1, "sh");
734         shtemp = Strspl(SAVE(strtmp2), doldol); /* For << */
735     }
736 #else /* !WINNT_NATIVE */
737     shtemp = Strspl(STRtmpsh, doldol);  /* For << */
738 #endif /* WINNT_NATIVE */
739
740     /*
741      * Record the interrupt states from the parent process. If the parent is
742      * non-interruptible our hand must be forced or we (and our children) won't
743      * be either. Our children inherit termination from our parent. We catch it
744      * only if we are the login shell.
745      */
746 #ifdef BSDSIGS
747     /* 
748      * PURIFY-2 claims that osv does not get 
749      * initialized after the sigvec call
750      */
751     setzero((char*) &osv, sizeof(osv));
752     /* parents interruptibility */
753     (void) mysigvec(SIGINT, NULL, &osv);
754     parintr = (signalfun_t) osv.sv_handler;
755     (void) mysigvec(SIGTERM, NULL, &osv);
756     parterm = (signalfun_t) osv.sv_handler;
757 #else                           /* BSDSIGS */
758     parintr = signal(SIGINT, SIG_IGN);  /* parents interruptibility */
759     (void) sigset(SIGINT, parintr);     /* ... restore */
760
761 # ifdef COHERENT
762     if (loginsh) /* it seems that SIGTERM is always set to SIG_IGN by */
763                  /* init/getty so it should be set to SIG_DFL - there may be */
764                  /* a better fix for this. */
765          parterm = SIG_DFL;
766     else
767 # else /* !COHERENT */
768     parterm = signal(SIGTERM, SIG_IGN); /* parents terminability */
769 # endif /* COHERENT */
770     (void) sigset(SIGTERM, parterm);    /* ... restore */
771
772 #endif /* BSDSIGS */
773
774
775 #ifdef TCF
776     /* Enable process migration on ourselves and our progeny */
777     (void) signal(SIGMIGRATE, SIG_DFL);
778 #endif /* TCF */
779
780     /*
781      * dspkanji/dspmbyte autosetting
782      */
783     /* PATCH IDEA FROM Issei.Suzuki VERY THANKS */
784 #if defined(DSPMBYTE)
785 #if defined(NLS) && defined(LC_CTYPE)
786     if (((tcp = setlocale(LC_CTYPE, NULL)) != NULL || (tcp = getenv("LANG")) != NULL) && !adrof(CHECK_MBYTEVAR)) {
787 #else
788     if ((tcp = getenv("LANG")) != NULL && !adrof(CHECK_MBYTEVAR)) {
789 #endif
790         autoset_dspmbyte(str2short(tcp));
791     }
792 #if defined(WINNT_NATIVE)
793     else if (!adrof(CHECK_MBYTEVAR))
794       nt_autoset_dspmbyte();
795 #endif /* WINNT_NATIVE */
796 #endif
797
798     fix_version();              /* publish the shell version */
799
800     if (argc > 1 && strcmp(argv[1], "--version") == 0) {
801         xprintf("%S\n", varval(STRversion));
802         xexit(0);
803     }
804     /*
805      * Process the arguments.
806      * 
807      * Note that processing of -v/-x is actually delayed till after script
808      * processing.
809      * 
810      * We set the first character of our name to be '-' if we are a shell 
811      * running interruptible commands.  Many programs which examine ps'es 
812      * use this to filter such shells out.
813      */
814     argc--, tempv++;
815     while (argc > 0 && (tcp = tempv[0])[0] == '-' &&
816            *++tcp != '\0' && !batch) {
817         do
818             switch (*tcp++) {
819
820             case 0:             /* -    Interruptible, no prompt */
821                 prompt = 0;
822                 setintr = 1;
823                 nofile = 1;
824                 break;
825
826             case 'b':           /* -b   Next arg is input file */
827                 batch = 1;
828                 break;
829
830             case 'c':           /* -c   Command input from arg */
831                 if (argc == 1)
832                     xexit(0);
833                 argc--, tempv++;
834 #ifdef M_XENIX
835                 /* Xenix Vi bug:
836                    it relies on a 7 bit environment (/bin/sh), so it
837                    pass ascii arguments with the 8th bit set */
838                 if (!strcmp(argv[0], "sh"))
839                   {
840                     char *p;
841
842                     for (p = tempv[0]; *p; ++p)
843                       *p &= ASCII;
844                   }
845 #endif
846                 arginp = SAVE(tempv[0]);
847
848                 /*
849                  * we put the command into a variable
850                  */
851                 if (arginp != NULL)
852                   set(STRcommand, quote(Strsave(arginp)), VAR_READWRITE);
853
854                 /*
855                  * * Give an error on -c arguments that end in * backslash to
856                  * ensure that you don't make * nonportable csh scripts.
857                  */
858                 {
859                     register int count;
860
861                     cp = arginp + Strlen(arginp);
862                     count = 0;
863                     while (cp > arginp && *--cp == '\\')
864                         ++count;
865                     if ((count & 1) != 0) {
866                         exiterr = 1;
867                         stderror(ERR_ARGC);
868                     }
869                 }
870                 prompt = 0;
871                 nofile = 1;
872                 break;
873             case 'd':           /* -d   Load directory stack from file */
874                 rdirs = 1;
875                 break;
876
877 #ifdef apollo
878             case 'D':           /* -D   Define environment variable */
879                 {
880                     register Char *dp;
881
882                     cp = str2short(tcp);
883                     if (dp = Strchr(cp, '=')) {
884                         *dp++ = '\0';
885                         tsetenv(cp, dp);
886                     }
887                     else
888                         tsetenv(cp, STRNULL);
889                 }
890                 *tcp = '\0';    /* done with this argument */
891                 break;
892 #endif /* apollo */
893
894             case 'e':           /* -e   Exit on any error */
895                 exiterr = 1;
896                 break;
897
898             case 'f':           /* -f   Fast start */
899                 fast = 1;
900                 break;
901
902             case 'i':           /* -i   Interactive, even if !intty */
903                 intact = 1;
904                 nofile = 1;
905                 break;
906
907             case 'm':           /* -m   read .cshrc (from su) */
908                 mflag = 1;
909                 break;
910
911             case 'n':           /* -n   Don't execute */
912                 noexec = 1;
913                 break;
914
915             case 'q':           /* -q   (Undoc'd) ... die on quit */
916                 quitit = 1;
917                 break;
918
919             case 's':           /* -s   Read from std input */
920                 nofile = 1;
921                 break;
922
923             case 't':           /* -t   Read one line from input */
924                 onelflg = 2;
925                 prompt = 0;
926                 nofile = 1;
927                 break;
928
929             case 'v':           /* -v   Echo hist expanded input */
930                 nverbose = 1;   /* ... later */
931                 break;
932
933             case 'x':           /* -x   Echo just before execution */
934                 nexececho = 1;  /* ... later */
935                 break;
936
937             case 'V':           /* -V   Echo hist expanded input */
938                 setNS(STRverbose);      /* NOW! */
939                 break;
940
941             case 'X':           /* -X   Echo just before execution */
942                 setNS(STRecho); /* NOW! */
943                 break;
944
945             case 'F':           /* Undocumented flag */
946                 /*
947                  * This will cause children to be created using fork instead of
948                  * vfork.
949                  */
950                 use_fork = 1;
951                 break;
952
953             case ' ':
954             case '\t':
955                 /* 
956                  * for O/S's that don't do the argument parsing right in 
957                  * "#!/foo -f " scripts
958                  */
959                 break;
960
961             default:            /* Unknown command option */
962                 exiterr = 1;
963                 stderror(ERR_TCSHUSAGE, tcp-1, progname);
964                 break;
965
966         } while (*tcp);
967         tempv++, argc--;
968     }
969
970     if (quitit)                 /* With all due haste, for debugging */
971         (void) signal(SIGQUIT, SIG_DFL);
972
973     /*
974      * Unless prevented by -, -c, -i, -s, or -t, if there are remaining
975      * arguments the first of them is the name of a shell file from which to
976      * read commands.
977      */
978     if (nofile == 0 && argc > 0) {
979         nofile = open(tempv[0], O_RDONLY|O_LARGEFILE);
980         if (nofile < 0) {
981             child = 1;          /* So this ... */
982             /* ... doesn't return */
983             stderror(ERR_SYSTEM, tempv[0], strerror(errno));
984         }
985 #ifdef O_TEXT
986         setmode(nofile, O_TEXT);
987 #endif
988         if (ffile != NULL)
989             xfree((ptr_t) ffile);
990         dolzero = 1;
991         ffile = SAVE(tempv[0]);
992         /* 
993          * Replace FSHIN. Handle /dev/std{in,out,err} specially
994          * since once they are closed we cannot open them again.
995          * In that case we use our own saved descriptors
996          */
997         if ((SHIN = dmove(nofile, FSHIN)) < 0) 
998             switch(nofile) {
999             case 0:
1000                 SHIN = FSHIN;
1001                 break;
1002             case 1:
1003                 SHIN = FSHOUT;
1004                 break;
1005             case 2:
1006                 SHIN = FSHDIAG;
1007                 break;
1008             default:
1009                 stderror(ERR_SYSTEM, tempv[0], strerror(errno));
1010                 break;
1011             }
1012         (void) close_on_exec(SHIN, 1);
1013         prompt = 0;
1014          /* argc not used any more */ tempv++;
1015     }
1016
1017     /* 
1018      * Call to closem() used to be part of initdesc(). Now called below where
1019      * the script name argument has become stdin. Kernel may have used a file
1020      * descriptor to hold the name of the script (setuid case) and this name
1021      * mustn't be lost by closing the fd too soon.
1022      */
1023     closem();
1024
1025     /*
1026      * Consider input a tty if it really is or we are interactive. but not for
1027      * editing (christos)
1028      */
1029     if (!(intty = isatty(SHIN))) {
1030         if (adrof(STRedit))
1031             unsetv(STRedit);
1032         editing = 0;
1033     }
1034     intty |= intact;
1035 #ifndef convex
1036     if (intty || (intact && isatty(SHOUT))) {
1037         if (!batch && (uid != euid || gid != egid)) {
1038             errno = EACCES;
1039             child = 1;          /* So this ... */
1040             /* ... doesn't return */
1041             stderror(ERR_SYSTEM, progname, strerror(errno));
1042         }
1043     }
1044 #endif /* convex */
1045     isoutatty = isatty(SHOUT);
1046     isdiagatty = isatty(SHDIAG);
1047     /*
1048      * Decide whether we should play with signals or not. If we are explicitly
1049      * told (via -i, or -) or we are a login shell (arg0 starts with -) or the
1050      * input and output are both the ttys("csh", or "csh</dev/ttyx>/dev/ttyx")
1051      * Note that in only the login shell is it likely that parent may have set
1052      * signals to be ignored
1053      */
1054     if (loginsh || intact || (intty && isatty(SHOUT)))
1055         setintr = 1;
1056     settell();
1057     /*
1058      * Save the remaining arguments in argv.
1059      */
1060     setq(STRargv, blk2short(tempv), &shvhed, VAR_READWRITE);
1061
1062     /*
1063      * Set up the prompt.
1064      */
1065     if (prompt) {
1066         if (tcsh)
1067             set(STRprompt, Strsave(STRdeftcshprompt), VAR_READWRITE);
1068         else
1069             set(STRprompt, Strsave(STRdefcshprompt), VAR_READWRITE);
1070         /* that's a meta-questionmark */
1071         set(STRprompt2, Strsave(STRmquestion), VAR_READWRITE);
1072         set(STRprompt3, Strsave(STRKCORRECT), VAR_READWRITE);
1073     }
1074
1075     /*
1076      * If we are an interactive shell, then start fiddling with the signals;
1077      * this is a tricky game.
1078      */
1079     shpgrp = mygetpgrp();
1080     opgrp = tpgrp = -1;
1081     if (setintr) {
1082         signalfun_t osig;
1083         **argv = '-';
1084         if (!quitit)            /* Wary! */
1085             (void) signal(SIGQUIT, SIG_IGN);
1086         (void) sigset(SIGINT, pintr);
1087         (void) sighold(SIGINT);
1088         (void) signal(SIGTERM, SIG_IGN);
1089
1090         /* 
1091          * No reason I can see not to save history on all these events..
1092          * Most usual occurrence is in a window system, where we're not a login
1093          * shell, but might as well be... (sg)
1094          * But there might be races when lots of shells exit together...
1095          * [this is also incompatible].
1096          * We have to be mre careful here. If the parent wants to 
1097          * ignore the signals then we leave them untouched...
1098          * We also only setup the handlers for shells that are trully
1099          * interactive.
1100          */
1101         osig = signal(SIGHUP, phup);    /* exit processing on HUP */
1102         if (!loginsh && osig == SIG_IGN)
1103             (void) signal(SIGHUP, osig);
1104 #ifdef SIGXCPU
1105         osig = signal(SIGXCPU, phup);   /* exit processing on XCPU */
1106         if (!loginsh && osig == SIG_IGN)
1107             (void) signal(SIGXCPU, osig);
1108 #endif
1109 #ifdef SIGXFSZ
1110         osig = signal(SIGXFSZ, phup);   /* exit processing on XFSZ */
1111         if (!loginsh && osig == SIG_IGN)
1112             (void) signal(SIGXFSZ, osig);
1113 #endif
1114
1115         if (quitit == 0 && arginp == 0) {
1116 #ifdef SIGTSTP
1117             (void) signal(SIGTSTP, SIG_IGN);
1118 #endif
1119 #ifdef SIGTTIN
1120             (void) signal(SIGTTIN, SIG_IGN);
1121 #endif
1122 #ifdef SIGTTOU
1123             (void) signal(SIGTTOU, SIG_IGN);
1124 #endif
1125             /*
1126              * Wait till in foreground, in case someone stupidly runs csh &
1127              * dont want to try to grab away the tty.
1128              */
1129             if (isatty(FSHDIAG))
1130                 f = FSHDIAG;
1131             else if (isatty(FSHOUT))
1132                 f = FSHOUT;
1133             else if (isatty(OLDSTD))
1134                 f = OLDSTD;
1135             else
1136                 f = -1;
1137
1138 #ifdef NeXT
1139             /* NeXT 2.0 /usr/etc/rlogind, does not set our process group! */
1140             if (shpgrp == 0) {
1141                 shpgrp = getpid();
1142                 (void) setpgid(0, shpgrp);
1143                 (void) tcsetpgrp(f, shpgrp);
1144             }
1145 #endif /* NeXT */
1146 #ifdef BSDJOBS                  /* if we have tty job control */
1147     retry:
1148             if ((tpgrp = tcgetpgrp(f)) != -1) {
1149                 if (tpgrp != shpgrp) {
1150                     signalfun_t old = signal(SIGTTIN, SIG_DFL);
1151                     (void) kill(0, SIGTTIN);
1152                     (void) signal(SIGTTIN, old);
1153                     goto retry;
1154                 }
1155                 /*
1156                  * Thanks to Matt Day for the POSIX references, and to
1157                  * Paul Close for the SGI clarification.
1158                  */
1159                 if (setdisc(f) != -1) {
1160                     opgrp = shpgrp;
1161                     shpgrp = getpid();
1162                     tpgrp = shpgrp;
1163                     if (tcsetpgrp(f, shpgrp) == -1) {
1164                         /*
1165                          * On hpux 7.03 this fails with EPERM. This happens on
1166                          * the 800 when opgrp != shpgrp at this point. (we were
1167                          * forked from a non job control shell)
1168                          * POSIX 7.2.4, says we failed because the process
1169                          * group specified did not belong to a process
1170                          * in the same session with the tty. So we set our
1171                          * process group and try again.
1172                          */
1173                         if (setpgid(0, shpgrp) == -1) {
1174                             xprintf("setpgid:");
1175                             goto notty;
1176                         }
1177                         if (tcsetpgrp(f, shpgrp) == -1) {
1178                             xprintf("tcsetpgrp:");
1179                             goto notty;
1180                         }
1181                     }
1182                     /*
1183                      * We check the process group now. If it is the same, then
1184                      * we don't need to set it again. On hpux 7.0 on the 300's
1185                      * if we set it again it fails with EPERM. This is the
1186                      * correct behavior according to POSIX 4.3.3 if the process
1187                      * was a session leader .
1188                      */
1189                     else if (shpgrp != mygetpgrp()) {
1190                         if(setpgid(0, shpgrp) == -1) {
1191                             xprintf("setpgid:");
1192                             goto notty;
1193                         }
1194                     }
1195 #ifdef IRIS4D
1196                     /*
1197                      * But on irix 3.3 we need to set it again, even if it is
1198                      * the same. We do that to tell the system that we
1199                      * need BSD process group compatibility.
1200                      */
1201                     else
1202                         (void) setpgid(0, shpgrp);
1203 #endif
1204                     (void) close_on_exec(dcopy(f, FSHTTY), 1);
1205                 }
1206                 else
1207                     tpgrp = -1;
1208             }
1209             if (tpgrp == -1) {
1210         notty:
1211                 xprintf(CGETS(11, 1, "Warning: no access to tty (%s).\n"),
1212                         strerror(errno));
1213                 xprintf(CGETS(11, 2, "Thus no job control in this shell.\n"));
1214                 /*
1215                  * Fix from:Sakari Jalovaara <sja@sirius.hut.fi> if we don't
1216                  * have access to tty, disable editing too
1217                  */
1218                 if (adrof(STRedit))
1219                     unsetv(STRedit);
1220                 editing = 0;
1221             }
1222 #else   /* BSDJOBS */           /* don't have job control, so frotz it */
1223             tpgrp = -1;
1224 #endif                          /* BSDJOBS */
1225         }
1226     }
1227     if ((setintr == 0) && (parintr == SIG_DFL))
1228         setintr = 1;
1229
1230 /*
1231  * SVR4 doesn't send a SIGCHLD when a child is stopped or continued if the
1232  * handler is installed with signal(2) or sigset(2).  sigaction(2) must
1233  * be used instead.
1234  *
1235  * David Dawes (dawes@physics.su.oz.au) Sept 1991
1236  */
1237
1238 #if SYSVREL > 3
1239     {
1240         struct sigaction act;
1241         act.sa_handler=pchild;
1242         (void) sigemptyset(&(act.sa_mask));     /* Don't block any extra sigs
1243                                                  * when the handler is called
1244                                                  */
1245         act.sa_flags=0;            /* want behaviour of sigset() without
1246                                     * SA_NOCLDSTOP
1247                                     */
1248
1249         if ((sigaction(SIGCHLD,&act,(struct sigaction *)NULL)) == -1)
1250             stderror(ERR_SYSTEM, "sigaction", strerror(errno));
1251     }
1252 #else /* SYSVREL <= 3 */
1253     (void) sigset(SIGCHLD, pchild);     /* while signals not ready */
1254 #endif /* SYSVREL <= 3 */
1255
1256
1257     if (intty && !arginp)       
1258         (void) ed_Setup(editing);/* Get the tty state, and set defaults */
1259                                  /* Only alter the tty state if editing */
1260     
1261     /*
1262      * Set an exit here in case of an interrupt or error reading the shell
1263      * start-up scripts.
1264      */
1265     osetintr = setintr;
1266     oparintr = parintr;
1267     reenter = setexit();        /* PWP */
1268     exitset++;
1269     haderr = 0;                 /* In case second time through */
1270     if (!fast && reenter == 0) {
1271         /* Will have varval(STRhome) here because set fast if don't */
1272         {
1273 #ifdef BSDSIGS
1274             sigmask_t omask = sigblock(sigmask(SIGINT));
1275 #else
1276             (void) sighold(SIGINT);
1277 #endif
1278             setintr = 0;
1279             parintr = SIG_IGN;  /* onintr in /etc/ files has no effect */
1280 #ifdef LOGINFIRST
1281 #ifdef _PATH_DOTLOGIN
1282             if (loginsh)
1283               (void) srcfile(_PATH_DOTLOGIN, 0, 0, NULL);
1284 #endif
1285 #endif
1286
1287 #ifdef _PATH_DOTCSHRC
1288             (void) srcfile(_PATH_DOTCSHRC, 0, 0, NULL);
1289 #endif
1290             if (!arginp && !onelflg && !havhash)
1291                 dohash(NULL,NULL);
1292 #ifndef LOGINFIRST
1293 #ifdef _PATH_DOTLOGIN
1294             if (loginsh)
1295                 (void) srcfile(_PATH_DOTLOGIN, 0, 0, NULL);
1296 #endif
1297 #endif
1298 #ifdef BSDSIGS
1299             (void) sigsetmask(omask);
1300 #else
1301             (void) sigrelse(SIGINT);
1302 #endif
1303             setintr = osetintr;
1304             parintr = oparintr;
1305         }
1306 #ifdef LOGINFIRST
1307         if (loginsh)
1308             (void) srccat(varval(STRhome), STRsldotlogin);
1309 #endif
1310         /* upward compat. */
1311         if (!srccat(varval(STRhome), STRsldottcshrc))
1312             (void) srccat(varval(STRhome), STRsldotcshrc);
1313
1314         if (!fast && !arginp && !onelflg && !havhash)
1315             dohash(NULL,NULL);
1316
1317         /*
1318          * Source history before .login so that it is available in .login
1319          */
1320         loadhist(NULL, 0);
1321 #ifndef LOGINFIRST
1322         if (loginsh)
1323             (void) srccat(varval(STRhome), STRsldotlogin);
1324 #endif
1325         if (!fast && (loginsh || rdirs))
1326             loaddirs(NULL);
1327     }
1328     /* Reset interrupt flag */
1329     setintr = osetintr;
1330     parintr = oparintr;
1331
1332     /* Initing AFTER .cshrc is the Right Way */
1333     if (intty && !arginp) {     /* PWP setup stuff */
1334         ed_Init();              /* init the new line editor */
1335 #ifdef SIG_WINDOW
1336         check_window_size(1);   /* mung environment */
1337 #endif                          /* SIG_WINDOW */
1338     }
1339
1340     /*
1341      * Now are ready for the -v and -x flags
1342      */
1343     if (nverbose)
1344         setNS(STRverbose);
1345     if (nexececho)
1346         setNS(STRecho);
1347     
1348     /*
1349      * All the rest of the world is inside this call. The argument to process
1350      * indicates whether it should catch "error unwinds".  Thus if we are a
1351      * interactive shell our call here will never return by being blown past on
1352      * an error.
1353      */
1354     process(setintr);
1355
1356     /*
1357      * Mop-up.
1358      */
1359     if (intty) {
1360         if (loginsh) {
1361             xprintf("logout\n");
1362             (void) close(SHIN);
1363             child = 1;
1364 #ifdef TESLA
1365             do_logout = 1;
1366 #endif                          /* TESLA */
1367             goodbye(NULL, NULL);
1368         }
1369         else {
1370             xprintf("exit\n");
1371         }
1372     }
1373     record();
1374     exitstat();
1375     return (0);
1376 }
1377
1378 void
1379 untty()
1380 {
1381 #ifdef BSDJOBS
1382     if (tpgrp > 0 && opgrp != shpgrp) {
1383         (void) setpgid(0, opgrp);
1384         (void) tcsetpgrp(FSHTTY, opgrp);
1385         (void) resetdisc(FSHTTY);
1386     }
1387 #endif /* BSDJOBS */
1388 }
1389
1390 void
1391 importpath(cp)
1392     Char   *cp;
1393 {
1394     register int i = 0;
1395     register Char *dp;
1396     register Char **pv;
1397     int     c;
1398
1399     for (dp = cp; *dp; dp++)
1400         if (*dp == PATHSEP)
1401             i++;
1402     /*
1403      * i+2 where i is the number of colons in the path. There are i+1
1404      * directories in the path plus we need room for a zero terminator.
1405      */
1406     pv = (Char **) xcalloc((size_t) (i + 2), sizeof(Char *));
1407     dp = cp;
1408     i = 0;
1409     if (*dp)
1410         for (;;) {
1411             if ((c = *dp) == PATHSEP || c == 0) {
1412                 *dp = 0;
1413                 pv[i++] = Strsave(*cp ? cp : STRdot);
1414                 if (c) {
1415                     cp = dp + 1;
1416                     *dp = PATHSEP;
1417                 }
1418                 else
1419                     break;
1420             }
1421 #ifdef WINNT_NATIVE
1422             else if (*dp == '\\')
1423                 *dp = '/';
1424 #endif /* WINNT_NATIVE */
1425             dp++;
1426         }
1427     pv[i] = 0;
1428     setq(STRpath, pv, &shvhed, VAR_READWRITE);
1429 }
1430
1431 /*
1432  * Source to the file which is the catenation of the argument names.
1433  */
1434 static int
1435 srccat(cp, dp)
1436     Char   *cp, *dp;
1437 {
1438     if (cp[0] == '/' && cp[1] == '\0') 
1439         return srcfile(short2str(dp), (mflag ? 0 : 1), 0, NULL);
1440     else {
1441         register Char *ep;
1442         char   *ptr;
1443         int rv;
1444
1445 #ifdef WINNT_NATIVE
1446         ep = cp;
1447         while(*ep)
1448             ep++;
1449         if (ep[-1] == '/' && dp[0] == '/') /* silly win95 */
1450             dp++;
1451 #endif /* WINNT_NATIVE */
1452
1453         ep = Strspl(cp, dp);
1454         ptr = short2str(ep);
1455
1456         rv = srcfile(ptr, (mflag ? 0 : 1), 0, NULL);
1457         xfree((ptr_t) ep);
1458         return rv;
1459     }
1460 }
1461
1462 /*
1463  * Source to a file putting the file descriptor in a safe place (> 2).
1464  */
1465 #ifndef WINNT_NATIVE
1466 static int
1467 #else
1468 int
1469 #endif /*WINNT_NATIVE*/
1470 srcfile(f, onlyown, flag, av)
1471     char   *f;
1472     bool    onlyown;
1473     int flag;
1474     Char **av;
1475 {
1476     register int unit;
1477
1478     if ((unit = open(f, O_RDONLY|O_LARGEFILE)) == -1) 
1479         return 0;
1480 #ifdef O_TEXT
1481     setmode(unit, O_TEXT);
1482 #endif
1483     unit = dmove(unit, -1);
1484
1485     (void) close_on_exec(unit, 1);
1486     srcunit(unit, onlyown, flag, av);
1487     return 1;
1488 }
1489
1490
1491 /*
1492  * Save the shell state, and establish new argument vector, and new input
1493  * fd.
1494  */
1495 static void
1496 st_save(st, unit, hflg, al, av)
1497     struct saved_state *st;
1498     int unit, hflg;
1499     Char **al, **av;
1500 {
1501     st->insource        = insource;
1502     st->SHIN            = SHIN;
1503     /* Want to preserve the meaning of "source file >output".
1504      * Save old descriptors, move new 0,1,2 to safe places and assign
1505      * them to SH* and let process() redo 0,1,2 from them.
1506      *
1507      * The macro returns true if d1 and d2 are good and they point to
1508      * different things.  If you don't avoid saving duplicate
1509      * descriptors, you really limit the depth of "source" recursion
1510      * you can do because of all the open file descriptors.  -IAN!
1511      */
1512 #define NEED_SAVE_FD(d1,d2) \
1513     (fstat(d1, &s1) != -1 && fstat(d2, &s2) != -1 \
1514         && (s1.st_ino != s2.st_ino || s1.st_dev != s2.st_dev) )
1515
1516     st->OLDSTD = st->SHOUT = st->SHDIAG = -1;/* test later to restore these */
1517     if (didfds) {
1518             struct stat s1, s2;
1519             if (NEED_SAVE_FD(0,OLDSTD))
1520                     st->OLDSTD = OLDSTD, OLDSTD = dmove(0, -1);
1521             if (NEED_SAVE_FD(1,SHOUT))
1522                     st->SHOUT = SHOUT, SHOUT = dmove(1, -1);
1523             if (NEED_SAVE_FD(2,SHDIAG))
1524                     st->SHDIAG = SHDIAG, SHDIAG = dmove(2, -1);
1525             donefds();
1526     }
1527
1528     st->intty           = intty;
1529     st->whyles          = whyles;
1530     st->gointr          = gointr;
1531     st->arginp          = arginp;
1532     st->evalp           = evalp;
1533     st->evalvec         = evalvec;
1534     st->alvecp          = alvecp;
1535     st->alvec           = alvec;
1536     st->onelflg         = onelflg;
1537     st->enterhist       = enterhist;
1538     if (hflg)
1539         st->HIST        = HIST;
1540     else
1541         st->HIST        = '\0';
1542     st->cantell         = cantell;
1543     cpybin(st->B, B);
1544
1545     /*
1546      * we can now pass arguments to source. 
1547      * For compatibility we do that only if arguments were really
1548      * passed, otherwise we keep the old, global $argv like before.
1549      */
1550     if (av != NULL && *av != NULL) {
1551         struct varent *vp;
1552         if ((vp = adrof(STRargv)) != NULL && vp->vec != NULL)
1553             st->argv = saveblk(vp->vec);
1554         else
1555             st->argv = NULL;
1556         setq(STRargv, saveblk(av), &shvhed, VAR_READWRITE);
1557     }
1558     else
1559         st->argv = NULL;
1560
1561     SHIN        = unit; /* Do this first */
1562
1563     /* Establish new input arena */
1564     {
1565         fbuf = NULL;
1566         fseekp = feobp = fblocks = 0;
1567         settell();
1568     }
1569
1570     arginp      = 0;
1571     onelflg     = 0;
1572     intty       = isatty(SHIN);
1573     whyles      = 0;
1574     gointr      = 0;
1575     evalvec     = 0;
1576     evalp       = 0;
1577     alvec       = al;
1578     alvecp      = 0;
1579     enterhist   = hflg;
1580     if (enterhist)
1581         HIST    = '\0';
1582     insource    = 1;
1583 }
1584
1585
1586 /*
1587  * Restore the shell to a saved state
1588  */
1589 static void
1590 st_restore(st, av)
1591     struct saved_state *st;
1592     Char **av;
1593 {
1594     if (st->SHIN == -1)
1595         return;
1596
1597     /* Reset input arena */
1598     {
1599         register int i;
1600         register Char** nfbuf = fbuf;
1601         register int nfblocks = fblocks;
1602
1603         fblocks = 0;
1604         fbuf = NULL;
1605         for (i = 0; i < nfblocks; i++)
1606             xfree((ptr_t) nfbuf[i]);
1607         xfree((ptr_t) nfbuf);
1608     }
1609     cpybin(B, st->B);
1610
1611     (void) close(SHIN);
1612
1613     insource    = st->insource;
1614     SHIN        = st->SHIN;
1615     if (st->OLDSTD != -1)
1616             (void)close(OLDSTD), OLDSTD = st->OLDSTD;
1617     if (st->SHOUT != -1)
1618             (void)close(SHOUT),  SHOUT = st->SHOUT;
1619     if (st->SHDIAG != -1)
1620             (void)close(SHDIAG), SHDIAG = st->SHDIAG;
1621     arginp      = st->arginp;
1622     onelflg     = st->onelflg;
1623     evalp       = st->evalp;
1624     evalvec     = st->evalvec;
1625     alvecp      = st->alvecp;
1626     alvec       = st->alvec;
1627     intty       = st->intty;
1628     whyles      = st->whyles;
1629     gointr      = st->gointr;
1630     if (st->HIST != '\0')
1631         HIST    = st->HIST;
1632     enterhist   = st->enterhist;
1633     cantell     = st->cantell;
1634
1635     if (st->argv != NULL)
1636         setq(STRargv, st->argv, &shvhed, VAR_READWRITE);
1637     else if (av != NULL  && *av != NULL && adrof(STRargv) != NULL)
1638         unsetv(STRargv);
1639 }
1640
1641 /*
1642  * Source to a unit.  If onlyown it must be our file or our group or
1643  * we don't chance it.  This occurs on ".cshrc"s and the like.
1644  */
1645 static void
1646 srcunit(unit, onlyown, hflg, av)
1647     register int unit;
1648     bool    onlyown;
1649     int hflg;
1650     Char **av;
1651 {
1652     struct saved_state st;
1653     st.SHIN = -1;       /* st_restore checks this */
1654
1655     if (unit < 0)
1656         return;
1657
1658     if (onlyown) {
1659         struct stat stb;
1660
1661         if (fstat(unit, &stb) < 0) {
1662             (void) close(unit);
1663             return;
1664         }
1665     }
1666
1667     getexit(st.oldexit);
1668
1669     if (setintr)
1670 #ifdef BSDSIGS
1671         st.mask = sigblock(sigmask(SIGINT));
1672 #else
1673         (void) sighold(SIGINT);
1674 #endif
1675
1676     /* Save the current state and move us to a new state */
1677     st_save(&st, unit, hflg, NULL, av);
1678
1679     /*
1680      * Now if we are allowing commands to be interrupted, we let ourselves be
1681      * interrupted.
1682      */
1683     if (setintr)
1684 #ifdef BSDSIGS
1685         (void) sigsetmask(st.mask);
1686 #else
1687         (void) sigrelse(SIGINT);
1688 #endif
1689
1690     /*
1691      * Bugfix for running out of memory by: Jak Kirman
1692      * <jak%cs.brown.edu@RELAY.CS.NET>.  Solution: pay attention to what
1693      * setexit() is returning because reenter _may_ be in a register, and
1694      * thus restored to 0 on a longjump(). (PWP: insert flames about
1695      * compiler-dependant code here) PWP: THANKS LOTS !!!
1696      *
1697      * PWP: think of this as like a LISP (unwind-protect ...)
1698      * thanks to Diana Smetters for pointing out how this _should_ be written
1699      */
1700 #ifdef cray
1701     st.reenter = 1;             /* assume non-zero return val */
1702     if (setexit() == 0) {
1703         st.reenter = 0;         /* Oh well, we were wrong */
1704 #else
1705     if ((st.reenter = setexit()) == 0) {
1706 #endif
1707         process(0);             /* 0 -> blow away on errors */
1708     }
1709
1710     if (setintr)
1711 #ifdef BSDSIGS
1712         (void) sigsetmask(st.mask);
1713 #else
1714         (void) sigrelse(SIGINT);
1715 #endif
1716
1717     /* Restore the old state */
1718     st_restore(&st, av);
1719     resexit(st.oldexit);
1720     /*
1721      * If process reset() (effectively an unwind) then we must also unwind.
1722      */
1723     if (st.reenter)
1724         stderror(ERR_SILENT);
1725 }
1726
1727
1728 /*ARGSUSED*/
1729 void
1730 goodbye(v, c)
1731     Char **v;
1732     struct command *c;
1733 {
1734     USE(c);
1735     record();
1736
1737     if (loginsh) {
1738         (void) sigset(SIGQUIT, SIG_IGN);
1739         (void) sigset(SIGINT, SIG_IGN);
1740         (void) sigset(SIGTERM, SIG_IGN);
1741         (void) sigset(SIGHUP, SIG_IGN);
1742         setintr = 0;            /* No interrupts after "logout" */
1743         /* Trap errors inside .logout */
1744         reenter = setexit();
1745         if (reenter != 0)
1746             exitstat();
1747         if (!(adrof(STRlogout)))
1748             set(STRlogout, Strsave(STRnormal), VAR_READWRITE);
1749 #ifdef _PATH_DOTLOGOUT
1750         (void) srcfile(_PATH_DOTLOGOUT, 0, 0, NULL);
1751 #endif
1752         if (adrof(STRhome))
1753             (void) srccat(varval(STRhome), STRsldtlogout);
1754 #ifdef TESLA
1755         do_logout = 1;
1756 #endif /* TESLA */
1757     }
1758     exitstat();
1759 }
1760
1761 void
1762 exitstat()
1763 {
1764 #ifdef PROF
1765     monitor(0);
1766 #endif
1767     /*
1768      * Note that if STATUS is corrupted (i.e. getn bombs) then error will exit
1769      * directly because we poke child here. Otherwise we might continue
1770      * unwarrantedly (sic).
1771      */
1772     child = 1;
1773
1774     xexit(getn(varval(STRstatus)));
1775 }
1776
1777 /*
1778  * in the event of a HUP we want to save the history
1779  */
1780 static  sigret_t
1781 phup(snum)
1782 int snum;
1783 {
1784     /*
1785      * There is no return from here,
1786      * so we are not going to release SIGHUP
1787      * anymore
1788      */
1789 #ifdef UNRELSIGS
1790     if (snum)
1791         (void) sigset(snum, SIG_IGN);
1792 #else
1793 # ifdef BSDSIGS
1794     (void) sigblock(sigmask(SIGHUP));
1795 # else
1796     (void) sighold(SIGHUP);
1797 # endif /* BSDSIGS */
1798 #endif /* UNRELSIGS */
1799
1800     if (loginsh) {
1801         set(STRlogout, Strsave(STRhangup), VAR_READWRITE);
1802 #ifdef _PATH_DOTLOGOUT
1803         (void) srcfile(_PATH_DOTLOGOUT, 0, 0, NULL);
1804 #endif
1805         if (adrof(STRhome))
1806             (void) srccat(varval(STRhome), STRsldtlogout);
1807     }
1808
1809     record();
1810
1811 #ifdef POSIXJOBS 
1812     /*
1813      * We kill the last foreground process group. It then becomes
1814      * responsible to propagate the SIGHUP to its progeny. 
1815      */
1816     {
1817         struct process *pp, *np;
1818
1819         for (pp = proclist.p_next; pp; pp = pp->p_next) {
1820             np = pp;
1821             /* 
1822              * Find if this job is in the foreground. It could be that
1823              * the process leader has exited and the foreground flag
1824              * is cleared for it.
1825              */
1826             do 
1827                 /*
1828                  * If a process is in the foreground we try to kill
1829                  * it's process group. If we succeed, then the 
1830                  * whole job is gone. Otherwise we keep going...
1831                  * But avoid sending HUP to the shell again.
1832                  */
1833                 if (((np->p_flags & PFOREGND) != 0) && np->p_jobid != shpgrp) {
1834                     np->p_flags &= ~PHUP;
1835                     if (killpg(np->p_jobid, SIGHUP) != -1) {
1836                         /* In case the job was suspended... */
1837 #ifdef SIGCONT
1838                         (void) killpg(np->p_jobid, SIGCONT);
1839 #endif
1840                         break;
1841                     }
1842                 }
1843             while ((np = np->p_friends) != pp);
1844         }
1845     }
1846 #endif /* POSIXJOBS */
1847
1848     xexit(snum);
1849 #ifndef SIGVOID
1850     return (snum);
1851 #endif
1852 }
1853
1854 static Char   *jobargv[2] = {STRjobs, 0};
1855
1856 /*
1857  * Catch an interrupt, e.g. during lexical input.
1858  * If we are an interactive shell, we reset the interrupt catch
1859  * immediately.  In any case we drain the shell output,
1860  * and finally go through the normal error mechanism, which
1861  * gets a chance to make the shell go away.
1862  */
1863 int     just_signaled;          /* bugfix by Michael Bloom (mg@ttidca.TTI.COM) */
1864
1865 #ifdef SIGVOID
1866 /*ARGSUSED*/
1867 #endif
1868 sigret_t
1869 pintr(snum)
1870 int snum;
1871 {
1872 #ifdef UNRELSIGS
1873     if (snum)
1874         (void) sigset(snum, pintr);
1875 #endif /* UNRELSIGS */
1876     just_signaled = 1;
1877     pintr1(1);
1878 #ifndef SIGVOID
1879     return (snum);
1880 #endif
1881 }
1882
1883 void
1884 pintr1(wantnl)
1885     bool    wantnl;
1886 {
1887     register Char **v;
1888 #ifdef BSDSIGS
1889     sigmask_t omask;
1890 #endif
1891
1892 #ifdef BSDSIGS
1893     omask = sigblock((sigmask_t) 0);
1894 #endif
1895     if (setintr) {
1896 #ifdef BSDSIGS
1897         (void) sigsetmask(omask & ~sigmask(SIGINT));
1898 #else
1899         (void) sigrelse(SIGINT);
1900 #endif
1901         if (pjobs) {
1902             pjobs = 0;
1903             xputchar('\n');
1904             dojobs(jobargv, NULL);
1905             stderror(ERR_NAME | ERR_INTR);
1906         }
1907     }
1908     /* MH - handle interrupted completions specially */
1909     {
1910         extern int InsideCompletion;
1911
1912         if (InsideCompletion)
1913             stderror(ERR_SILENT);
1914     }
1915     /* JV - Make sure we shut off inputl */
1916     {
1917         extern Char GettingInput;
1918
1919         (void) Cookedmode();
1920         GettingInput = 0;
1921     }
1922 #ifdef BSDSIGS
1923     (void) sigsetmask(omask & ~sigmask(SIGCHLD));
1924 #else
1925     if (setintr)
1926         (void) sighold(SIGINT);
1927     (void) sigrelse(SIGCHLD);
1928 #endif
1929     drainoline();
1930 #if !defined(_VMS_POSIX) && !defined(WINNT_NATIVE)
1931     (void) endpwent();
1932 #endif /* !_VMS_POSIX && !WINNT_NATIVE */
1933
1934     /*
1935      * If we have an active "onintr" then we search for the label. Note that if
1936      * one does "onintr -" then we shan't be interruptible so we needn't worry
1937      * about that here.
1938      */
1939     if (gointr) {
1940         gotolab(gointr);
1941         timflg = 0;
1942         if ((v = pargv) != 0)
1943             pargv = 0, blkfree(v);
1944         if ((v = gargv) != 0)
1945             gargv = 0, blkfree(v);
1946         reset();
1947     }
1948     else if (intty && wantnl) {
1949         if (editing) {
1950             /* 
1951              * If we are editing a multi-line input command, and move to
1952              * the beginning of the line, we don't want to trash it when
1953              * we hit ^C
1954              */
1955             PastBottom();
1956             ClearLines();
1957             ClearDisp();
1958         }
1959         else {
1960             /* xputchar('\n'); *//* Some like this, others don't */
1961             (void) putraw('\r');
1962             (void) putraw('\n');
1963         }
1964     }
1965     stderror(ERR_SILENT);
1966 }
1967
1968 /*
1969  * Process is the main driving routine for the shell.
1970  * It runs all command processing, except for those within { ... }
1971  * in expressions (which is run by a routine evalav in sh.exp.c which
1972  * is a stripped down process), and `...` evaluation which is run
1973  * also by a subset of this code in sh.glob.c in the routine backeval.
1974  *
1975  * The code here is a little strange because part of it is interruptible
1976  * and hence freeing of structures appears to occur when none is necessary
1977  * if this is ignored.
1978  *
1979  * Note that if catch is not set then we will unwind on any error.
1980  * If an end-of-file occurs, we return.
1981  */
1982 static struct command *savet = NULL;
1983 void
1984 process(catch)
1985     bool    catch;
1986 {
1987     extern char Expand;
1988     jmp_buf_t osetexit;
1989     /* PWP: This might get nuked my longjmp so don't make it a register var */
1990     struct command *t = savet;
1991
1992     savet = NULL;
1993     getexit(osetexit);
1994     for (;;) {
1995
1996         pendjob();
1997
1998         /* This was leaking memory badly, particularly when sourcing
1999          * files, etc.. For whatever reason we were arriving here with
2000          * allocated pointers still active, and the code was simply
2001          * overwriting them.  I can't say I fully understand the
2002          * control flow here, but according to Purify this particular
2003          * leak has been plugged, and I haven't noticed any ill
2004          * effects.. (sg)
2005          */
2006         if (paraml.next && paraml.next != &paraml)
2007             freelex(&paraml);
2008
2009         paraml.next = paraml.prev = &paraml;
2010         paraml.word = STRNULL;
2011         (void) setexit();
2012         justpr = enterhist;     /* execute if not entering history */
2013
2014         /*
2015          * Interruptible during interactive reads
2016          */
2017         if (setintr)
2018 #ifdef BSDSIGS
2019             (void) sigsetmask(sigblock((sigmask_t) 0) & ~sigmask(SIGINT));
2020 #else
2021             (void) sigrelse(SIGINT);
2022 #endif
2023
2024
2025         /*
2026          * For the sake of reset()
2027          */
2028         freelex(&paraml);
2029         if (savet)
2030             freesyn(savet), savet = NULL;
2031
2032         if (haderr) {
2033             if (!catch) {
2034                 /* unwind */
2035                 doneinp = 0;
2036                 savet = t;
2037                 resexit(osetexit);
2038                 reset();
2039             }
2040             haderr = 0;
2041             /*
2042              * Every error is eventually caught here or the shell dies.  It is
2043              * at this point that we clean up any left-over open files, by
2044              * closing all but a fixed number of pre-defined files.  Thus
2045              * routines don't have to worry about leaving files open due to
2046              * deeper errors... they will get closed here.
2047              */
2048             closem();
2049             continue;
2050         }
2051         if (doneinp) {
2052             doneinp = 0;
2053             break;
2054         }
2055         if (chkstop)
2056             chkstop--;
2057         if (neednote)
2058             pnote();
2059         if (intty && prompt && evalvec == 0) {
2060             just_signaled = 0;
2061             mailchk();
2062             /*
2063              * Watch for logins/logouts. Next is scheduled commands stored
2064              * previously using "sched." Then execute periodic commands.
2065              * Following that, the prompt precmd is run.
2066              */
2067 #ifndef HAVENOUTMP
2068             watch_login(0);
2069 #endif /* !HAVENOUTMP */
2070             sched_run(0);
2071             period_cmd();
2072             precmd();
2073             /*
2074              * If we are at the end of the input buffer then we are going to
2075              * read fresh stuff. Otherwise, we are rereading input and don't
2076              * need or want to prompt.
2077              */
2078             if (fseekp == feobp && aret == TCSH_F_SEEK)
2079                 printprompt(0, NULL);
2080             flush();
2081             setalarm(1);
2082         }
2083         if (seterr) {
2084             xfree((ptr_t) seterr);
2085             seterr = NULL;
2086         }
2087
2088         /*
2089          * Echo not only on VERBOSE, but also with history expansion. If there
2090          * is a lexical error then we forego history echo.
2091          */
2092         if ((lex(&paraml) && !seterr && intty && !tellwhat && !Expand && 
2093              !whyles) || adrof(STRverbose)) {
2094             int odidfds = didfds;
2095             haderr = 1;
2096             didfds = 0;
2097             prlex(&paraml);
2098             flush();
2099             haderr = 0;
2100             didfds = odidfds;
2101         }
2102         (void) alarm(0);        /* Autologout OFF */
2103
2104         /*
2105          * The parser may lose space if interrupted.
2106          */
2107         if (setintr)
2108 #ifdef BSDSIGS
2109             (void) sigblock(sigmask(SIGINT));
2110 #else
2111             (void) sighold(SIGINT);
2112 #endif
2113
2114         /*
2115          * Save input text on the history list if reading in old history, or it
2116          * is from the terminal at the top level and not in a loop.
2117          * 
2118          * PWP: entry of items in the history list while in a while loop is done
2119          * elsewhere...
2120          */
2121         if (enterhist || (catch && intty && !whyles && !tellwhat && !arun))
2122             savehist(&paraml, enterhist > 1);
2123
2124         if (Expand && seterr)
2125             Expand = 0;
2126
2127         /*
2128          * Print lexical error messages, except when sourcing history lists.
2129          */
2130         if (!enterhist && seterr)
2131             stderror(ERR_OLD);
2132
2133         /*
2134          * If had a history command :p modifier then this is as far as we
2135          * should go
2136          */
2137         if (justpr)
2138             reset();
2139
2140         /*
2141          * If had a tellwhat from twenex() then do
2142          */
2143         if (tellwhat) {
2144             (void) tellmewhat(&paraml, NULL);
2145             reset();
2146         }
2147
2148         alias(&paraml);
2149
2150 #ifdef BSDJOBS
2151         /*
2152          * If we are interactive, try to continue jobs that we have stopped
2153          */
2154         if (prompt)
2155             continue_jobs(&paraml);
2156 #endif                          /* BSDJOBS */
2157
2158         /*
2159          * Check to see if the user typed "rm * .o" or something
2160          */
2161         if (prompt)
2162             rmstar(&paraml);
2163         /*
2164          * Parse the words of the input into a parse tree.
2165          */
2166         savet = syntax(paraml.next, &paraml, 0);
2167         if (seterr)
2168             stderror(ERR_OLD);
2169
2170         postcmd();
2171         /*
2172          * Execute the parse tree From: Michael Schroeder
2173          * <mlschroe@immd4.informatik.uni-erlangen.de> was execute(t, tpgrp);
2174          */
2175         execute(savet, (tpgrp > 0 ? tpgrp : -1), NULL, NULL, TRUE);
2176
2177         /*
2178          * Made it!
2179          */
2180         freelex(&paraml);
2181         freesyn(savet), savet = NULL;
2182 #ifdef SIG_WINDOW
2183         if (windowchg || (catch && intty && !whyles && !tellwhat)) {
2184             windowchg = 0;
2185             (void) check_window_size(0);        /* for window systems */
2186         }
2187 #endif /* SIG_WINDOW */
2188         set(STR_, Strsave(InputBuf), VAR_READWRITE | VAR_NOGLOB);
2189     }
2190     savet = t;
2191     resexit(osetexit);
2192 }
2193
2194 /*ARGSUSED*/
2195 void
2196 dosource(t, c)
2197     register Char **t;
2198     struct command *c;
2199 {
2200     register Char *f;
2201     bool    hflg = 0;
2202     extern int bequiet;
2203     char    buf[BUFSIZE];
2204
2205     USE(c);
2206     t++;
2207     if (*t && eq(*t, STRmh)) {
2208         if (*++t == NULL)
2209             stderror(ERR_NAME | ERR_HFLAG);
2210         hflg++;
2211     }
2212     else if (*t && eq(*t, STRmm)) {
2213         if (*++t == NULL)
2214             stderror(ERR_NAME | ERR_MFLAG);
2215         hflg = 2;
2216     }
2217
2218     f = globone(*t++, G_ERROR);
2219     (void) strcpy(buf, short2str(f));
2220     xfree((ptr_t) f);
2221     gflag = 0, tglob(t);
2222     if (gflag) {
2223         t = globall(t);
2224         if (t == 0)
2225             stderror(ERR_NAME | ERR_NOMATCH);
2226     } else {
2227         t = saveblk(t);
2228         trim(t);
2229     }
2230     if ((!srcfile(buf, 0, hflg, t)) && (!hflg) && (!bequiet))
2231         stderror(ERR_SYSTEM, buf, strerror(errno));
2232 }
2233
2234 /*
2235  * Check for mail.
2236  * If we are a login shell, then we don't want to tell
2237  * about any mail file unless its been modified
2238  * after the time we started.
2239  * This prevents us from telling the user things he already
2240  * knows, since the login program insists on saying
2241  * "You have mail."
2242  */
2243
2244 /*
2245  * The AMS version.
2246  * This version checks if the file is a directory, and if so,
2247  * tells you the number of files in it, otherwise do the old thang.
2248  * The magic "+1" in the time calculation is to compensate for
2249  * an AFS bug where directory mtimes are set to 1 second in
2250  * the future.
2251  */
2252
2253 static void
2254 mailchk()
2255 {
2256     register struct varent *v;
2257     register Char **vp;
2258     time_t  t;
2259     int     intvl, cnt;
2260     struct stat stb;
2261     bool    new;
2262
2263     v = adrof(STRmail);
2264     if (v == NULL || v->vec == NULL)
2265         return;
2266     (void) time(&t);
2267     vp = v->vec;
2268     cnt = blklen(vp);
2269     intvl = (cnt && number(*vp)) ? (--cnt, getn(*vp++)) : MAILINTVL;
2270     if (intvl < 1)
2271         intvl = 1;
2272     if (chktim + intvl > t)
2273         return;
2274     for (; *vp; vp++) {
2275         char *filename = short2str(*vp);
2276         char *mboxdir = filename;
2277
2278         if (stat(filename, &stb) < 0)
2279             continue;
2280 #if defined(BSDTIMES) || defined(_SEQUENT_)
2281         new = stb.st_mtime > time0.tv_sec;
2282 #else
2283         new = stb.st_mtime > seconds0;
2284 #endif
2285         if (S_ISDIR(stb.st_mode)) {
2286             DIR *mailbox;
2287             int mailcount = 0;
2288             char tempfilename[MAXPATHLEN];
2289             struct stat stc;
2290
2291             xsnprintf(tempfilename, MAXPATHLEN, "%s/new", filename);
2292
2293             if (stat(tempfilename, &stc) != -1 && S_ISDIR(stc.st_mode)) {
2294                 /*
2295                  * "filename/new" exists and is a directory; you are
2296                  * using Qmail.
2297                  */
2298                 stb = stc;
2299 #if defined(BSDTIMES) || defined(_SEQUENT_)
2300                 new = stb.st_mtime > time0.tv_sec;
2301 #else
2302                 new = stb.st_mtime > seconds0;
2303 #endif
2304                 mboxdir = tempfilename;
2305             }
2306
2307             if (stb.st_mtime <= chktim + 1 || (loginsh && !new))
2308                 continue;
2309
2310             if ((mailbox = opendir(mboxdir)) == NULL)
2311                 continue;
2312
2313             /* skip . and .. */
2314             if (!readdir(mailbox) || !readdir(mailbox))
2315                 continue;
2316
2317             while (readdir(mailbox))
2318                 mailcount++;
2319
2320             if (mailcount == 0)
2321                 continue;
2322
2323             if (cnt == 1)
2324                 xprintf(CGETS(11, 3, "You have %d mail messages.\n"),
2325                         mailcount);
2326             else
2327                 xprintf(CGETS(11, 4, "You have %d mail messages in %s.\n"),
2328                         mailcount, filename);
2329         }
2330         else {
2331             if (stb.st_size == 0 || stb.st_atime > stb.st_mtime ||
2332                 (stb.st_atime <= chktim && stb.st_mtime <= chktim) ||
2333                 (loginsh && !new))
2334                 continue;
2335             if (cnt == 1)
2336                 xprintf(CGETS(11, 5, "You have %smail.\n"),
2337                         new ? CGETS(11, 6, "new ") : "");
2338             else
2339                 xprintf(CGETS(11, 7, "You have %smail in %s.\n"),
2340                         new ? CGETS(11, 6, "new ") : "", filename);
2341         }
2342     }
2343     chktim = t;
2344 }
2345
2346 /*
2347  * Extract a home directory from the password file
2348  * The argument points to a buffer where the name of the
2349  * user whose home directory is sought is currently.
2350  * We write the home directory of the user back there.
2351  */
2352 int
2353 gethdir(home)
2354     Char   *home;
2355 {
2356     Char   *h;
2357
2358     /*
2359      * Is it us?
2360      */
2361     if (*home == '\0') {
2362         if ((h = varval(STRhome)) != STRNULL) {
2363             (void) Strcpy(home, h);
2364             return 0;
2365         }
2366         else
2367             return 1;
2368     }
2369
2370     /*
2371      * Look in the cache
2372      */
2373     if ((h = gettilde(home)) == NULL)
2374         return 1;
2375     else {
2376         (void) Strcpy(home, h);
2377         return 0;
2378     }
2379 }
2380
2381 /*
2382  * Move the initial descriptors to their eventual
2383  * resting places, closing all other units.
2384  */
2385 void
2386 initdesc()
2387 {
2388 #ifdef NLS_BUGS
2389 #ifdef NLS_CATALOGS
2390     (void)catclose(catd);
2391 #endif /* NLS_CATALOGS */
2392 #endif /* NLS_BUGS */
2393
2394
2395     didfds = 0;                 /* 0, 1, 2 aren't set up */
2396     (void) close_on_exec(SHIN = dcopy(0, FSHIN), 1);
2397     (void) close_on_exec(SHOUT = dcopy(1, FSHOUT), 1);
2398     (void) close_on_exec(SHDIAG = dcopy(2, FSHDIAG), 1);
2399     (void) close_on_exec(OLDSTD = dcopy(SHIN, FOLDSTD), 1);
2400 #ifndef CLOSE_ON_EXEC
2401     didcch = 0;                 /* Havent closed for child */
2402 #endif /* CLOSE_ON_EXEC */
2403     isdiagatty = isatty(SHDIAG);
2404     isoutatty = isatty(SHOUT);
2405 #ifdef NLS_BUGS
2406 #ifdef NLS_CATALOGS
2407     nlsinit();
2408 #endif /* NLS_CATALOGS */
2409 #endif /* NLS_BUGS */
2410 }
2411
2412
2413 void
2414 #ifdef PROF
2415 done(i)
2416 #else
2417 xexit(i)
2418 #endif
2419     int     i;
2420 {
2421 #ifdef TESLA
2422     if (loginsh && do_logout) {
2423         /* this is to send hangup signal to the develcon */
2424         /* we toggle DTR. clear dtr - sleep 1 - set dtr */
2425         /* ioctl will return ENOTTY for pty's but we ignore it   */
2426         /* exitstat will run after disconnect */
2427         /* we sleep for 2 seconds to let things happen in */
2428         /* .logout and rechist() */
2429 #ifdef TIOCCDTR
2430         (void) sleep(2);
2431         (void) ioctl(FSHTTY, TIOCCDTR, NULL);
2432         (void) sleep(1);
2433         (void) ioctl(FSHTTY, TIOCSDTR, NULL);
2434 #endif /* TIOCCDTR */
2435     }
2436 #endif /* TESLA */
2437
2438     {
2439         struct process *pp, *np;
2440
2441         /* Kill all processes marked for hup'ing */
2442         for (pp = proclist.p_next; pp; pp = pp->p_next) {
2443             np = pp;
2444             do 
2445                 if ((np->p_flags & PHUP) && np->p_jobid != shpgrp) {
2446                     if (killpg(np->p_jobid, SIGHUP) != -1) {
2447                         /* In case the job was suspended... */
2448 #ifdef SIGCONT
2449                         (void) killpg(np->p_jobid, SIGCONT);
2450 #endif
2451                         break;
2452                     }
2453                 }
2454             while ((np = np->p_friends) != pp);
2455         }
2456     }
2457     untty();
2458 #ifdef NLS_CATALOGS
2459     /*
2460      * We need to call catclose, because SVR4 leaves symlinks behind otherwise
2461      * in the catalog directories. We cannot close on a vforked() child,
2462      * because messages will stop working on the parent too.
2463      */
2464     if (child == 0)
2465         (void) catclose(catd);
2466 #endif /* NLS_CATALOGS */
2467 #ifdef WINNT_NATIVE
2468     nt_cleanup();
2469 #endif /* WINNT_NATIVE */
2470     _exit(i);
2471 }
2472
2473 #ifndef _PATH_DEFPATH
2474 static Char **
2475 defaultpath()
2476 {
2477     char   *ptr;
2478     Char  **blk, **blkp;
2479     struct stat stb;
2480
2481     blkp = blk = (Char **) xmalloc((size_t) sizeof(Char *) * 10);
2482
2483 #ifndef NODOT
2484 # ifndef DOTLAST
2485     *blkp++ = Strsave(STRdot);
2486 # endif
2487 #endif
2488
2489 #define DIRAPPEND(a)  \
2490         if (stat(ptr = a, &stb) == 0 && S_ISDIR(stb.st_mode)) \
2491                 *blkp++ = SAVE(ptr)
2492
2493 #ifdef _PATH_LOCAL
2494     DIRAPPEND(_PATH_LOCAL);
2495 #endif
2496
2497 #ifdef _PATH_USRUCB
2498     DIRAPPEND(_PATH_USRUCB);
2499 #endif
2500
2501 #ifdef _PATH_USRBSD
2502     DIRAPPEND(_PATH_USRBSD);
2503 #endif
2504
2505 #ifdef _PATH_BIN
2506     DIRAPPEND(_PATH_BIN);
2507 #endif
2508
2509 #ifdef _PATH_USRBIN
2510     DIRAPPEND(_PATH_USRBIN);
2511 #endif
2512
2513 #undef DIRAPPEND
2514
2515 #ifndef NODOT
2516 # ifdef DOTLAST
2517     *blkp++ = Strsave(STRdot);
2518 # endif
2519 #endif
2520     *blkp = NULL;
2521     return (blk);
2522 }
2523 #endif
2524
2525 static void
2526 record()
2527 {
2528     if (!fast) {
2529         recdirs(NULL, adrof(STRsavedirs) != NULL);
2530         rechist(NULL, adrof(STRsavehist) != NULL);
2531     }
2532 }