sh.c revision 167465
11539Srgrimes/* $Header: /p/tcsh/cvsroot/tcsh/sh.c,v 3.136 2007/02/22 21:57:37 christos Exp $ */
21539Srgrimes/*
31539Srgrimes * sh.c: Main shell routines
41539Srgrimes */
51539Srgrimes/*-
61539Srgrimes * Copyright (c) 1980, 1991 The Regents of the University of California.
71539Srgrimes * All rights reserved.
81539Srgrimes *
91539Srgrimes * Redistribution and use in source and binary forms, with or without
101539Srgrimes * modification, are permitted provided that the following conditions
111539Srgrimes * are met:
121539Srgrimes * 1. Redistributions of source code must retain the above copyright
131539Srgrimes *    notice, this list of conditions and the following disclaimer.
141539Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
151539Srgrimes *    notice, this list of conditions and the following disclaimer in the
161539Srgrimes *    documentation and/or other materials provided with the distribution.
171539Srgrimes * 3. Neither the name of the University nor the names of its contributors
181539Srgrimes *    may be used to endorse or promote products derived from this software
191539Srgrimes *    without specific prior written permission.
201539Srgrimes *
211539Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
221539Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
231539Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
241539Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
251539Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
261539Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
271539Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
281539Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
291539Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
301539Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
311539Srgrimes * SUCH DAMAGE.
321539Srgrimes */
3323657Speter#define EXTERN	/* Intern */
3455033Sbde#include "sh.h"
351539Srgrimes
361539Srgrimes#ifndef lint
371539Srgrimeschar    copyright[] =
381539Srgrimes"@(#) Copyright (c) 1991 The Regents of the University of California.\n\
391539Srgrimes All rights reserved.\n";
401539Srgrimes#endif /* not lint */
4193514Smike
421539SrgrimesRCSID("$tcsh: sh.c,v 3.136 2007/02/22 21:57:37 christos Exp $")
43123257Smarcel
4493514Smike#include "tc.h"
451539Srgrimes#include "ed.h"
46102227Smike#include "tw.h"
47102227Smike
48102227Smikeextern int MapsAreInited;
4993514Smikeextern int NLSMapsAreInited;
5093514Smike
51108381Smike/*
52108381Smike * C Shell
53108381Smike *
54108381Smike * Bill Joy, UC Berkeley, California, USA
55108381Smike * October 1978, May 1980
56108381Smike *
57108381Smike * Jim Kulp, IIASA, Laxenburg, Austria
58108381Smike * April 1980
59108381Smike *
60108381Smike * Filename recognition added:
61102227Smike * Ken Greer, Ind. Consultant, Palo Alto CA
62102227Smike * October 1983.
63102227Smike *
6493514Smike * Karl Kleinpaste, Computer Consoles, Inc.
6593514Smike * Added precmd, periodic/tperiod, prompt changes,
66102227Smike * directory stack hack, and login watch.
67102227Smike * Sometime March 1983 - Feb 1984.
68102227Smike *
6993514Smike * Added scheduled commands, including the "sched" command,
7093514Smike * plus the call to sched_run near the precmd et al
71102227Smike * routines.
72108381Smike * Upgraded scheduled events for running events while
73102227Smike * sitting idle at command input.
7493514Smike *
7593514Smike * Paul Placeway, Ohio State
76108381Smike * added stuff for running with twenex/inputl  9 Oct 1984.
77108381Smike *
78108381Smike * ported to Apple Unix (TM) (OREO)  26 -- 29 Jun 1987
79108381Smike */
8093514Smike
811539Srgrimesjmp_buf_t reslab INIT_ZERO_STRUCT;
821539Srgrimes
831539Srgrimesstatic const char tcshstr[] = "tcsh";
841539Srgrimes
8598269Swollmanstruct sigaction parintr;	/* Parents interrupt catch */
8637566Sbdestruct sigaction parterm;	/* Parents terminate catch */
8737566Sbde
8837566Sbde#ifdef TESLA
8937566Sbdeint do_logout = 0;
9037509Sdt#endif /* TESLA */
9137509Sdt
92103729Swollman
93103729Swollmanint    use_fork = 0;		/* use fork() instead of vfork()? */
94103729Swollman
95103729Swollman/*
96103729Swollman * Magic pointer values. Used to specify other invalid conditions aside
97103729Swollman * from null.
98103729Swollman */
99103729Swollmanstatic Char	INVCHAR;
100103729SwollmanChar    *INVPTR = &INVCHAR;
101103729SwollmanChar    **INVPPTR = &INVPTR;
102103729Swollman
103103729Swollmanstatic int    fast = 0;
104103729Swollmanstatic int    mflag = 0;
105103729Swollmanstatic int    prompt = 1;
106153005Sdavidxuint     enterhist = 0;
107103729Swollmanint    tellwhat = 0;
108103729Swollmantime_t  t_period;
109103729SwollmanChar  *ffile = NULL;
110180360Sdavidxuint	dolzero = 0;
111153005Sdavidxuint	insource = 0;
112103729Swollmanint	exitset = 0;
113103729Swollmanstatic time_t  chktim;		/* Time mail last checked */
114175431Sdavidxuchar *progname;
115103729Swollmanint tcsh;
116103729Swollman
117103729Swollman/*
118103729Swollman * This preserves the input state of the shell. It is used by
119103729Swollman * st_save and st_restore to manupulate shell state.
120103729Swollman */
121103729Swollmanstruct saved_state {
122103729Swollman    int		  insource;
123103729Swollman    int		  OLDSTD;
124103729Swollman    int		  SHIN;
125103729Swollman    int		  SHOUT;
126103729Swollman    int		  SHDIAG;
127103729Swollman    int		  intty;
128103729Swollman    struct whyle *whyles;
129103729Swollman    Char 	 *gointr;
130103729Swollman    Char 	 *arginp;
131103729Swollman    Char	 *evalp;
132103729Swollman    Char	**evalvec;
133103729Swollman    Char	 *alvecp;
134103729Swollman    Char	**alvec;
135103729Swollman    int		  onelflg;
136103729Swollman    int	  enterhist;
137103729Swollman    Char	**argv;
138103729Swollman    Char	**av;
139103729Swollman    Char	  HIST;
140103729Swollman    int	  cantell;
141103729Swollman    struct Bin	  B;
142103729Swollman};
143103729Swollman
144103729Swollmanstatic	int		  srccat	(Char *, Char *);
145103729Swollman#ifndef WINNT_NATIVE
146103729Swollmanstatic	int		  srcfile	(const char *, int, int, Char **);
147103729Swollman#else
148103729Swollmanint		  srcfile	(const char *, int, int, Char **);
149103729Swollman#endif /*WINNT_NATIVE*/
150103729Swollmanstatic	void		  srcunit	(int, int, int, Char **);
151103729Swollmanstatic	void		  mailchk	(void);
152103729Swollman#ifndef _PATH_DEFPATH
153103729Swollmanstatic	Char	 	**defaultpath	(void);
154105045Smike#endif
155103929Swollmanstatic	void		  record	(void);
156103729Swollmanstatic	void		  st_save	(struct saved_state *, int, int,
157103729Swollman					 Char **, Char **);
158103729Swollmanstatic	void		  st_restore	(void *);
159103729Swollman
160103729Swollman	int		  main		(int, char **);
161103729Swollman
162103729Swollmanint
163103729Swollmanmain(int argc, char **argv)
164103729Swollman{
165103729Swollman    int batch = 0;
166103729Swollman    volatile int nexececho = 0;
167103729Swollman    int nofile = 0;
168103729Swollman    volatile int nverbose = 0;
169103729Swollman    volatile int rdirs = 0;
170103729Swollman    int quitit = 0;
171103729Swollman    Char *cp;
172103729Swollman#ifdef AUTOLOGOUT
173103729Swollman    Char *cp2;
174103729Swollman#endif
175103729Swollman    char *tcp, *ttyn;
176103729Swollman    int f, reenter;
177103729Swollman    char **tempv;
178103729Swollman    int osetintr;
179103729Swollman    struct sigaction oparintr;
180103729Swollman
181103729Swollman#ifdef WINNT_NATIVE
182103729Swollman    nt_init();
183103729Swollman#endif /* WINNT_NATIVE */
184103729Swollman#if defined(NLS_CATALOGS) && defined(LC_MESSAGES)
185103729Swollman    (void) setlocale(LC_MESSAGES, "");
186103729Swollman#endif /* NLS_CATALOGS && LC_MESSAGES */
187103729Swollman
188103729Swollman#ifdef NLS
189103729Swollman# ifdef LC_CTYPE
190103729Swollman    (void) setlocale(LC_CTYPE, ""); /* for iscntrl */
191103729Swollman# endif /* LC_CTYPE */
192103729Swollman#endif /* NLS */
193103729Swollman
194103729Swollman    nlsinit();
195103729Swollman
196103729Swollman#ifdef MALLOC_TRACE
197103729Swollman    mal_setstatsfile(fdopen(dmove(xopen("/tmp/tcsh.trace",
198103729Swollman	O_WRONLY|O_CREAT|O_LARGEFILE, 0666), 25), "w"));
199103729Swollman    mal_trace(1);
200103729Swollman#endif /* MALLOC_TRACE */
201103729Swollman
202103729Swollman#if !(defined(BSDTIMES) || defined(_SEQUENT_)) && defined(POSIX)
203103729Swollman# ifdef _SC_CLK_TCK
204103729Swollman    clk_tck = (clock_t) sysconf(_SC_CLK_TCK);
205103729Swollman# else /* ! _SC_CLK_TCK */
206103729Swollman#  ifdef CLK_TCK
207103729Swollman    clk_tck = CLK_TCK;
208103729Swollman#  else /* !CLK_TCK */
209103729Swollman    clk_tck = HZ;
210103729Swollman#  endif /* CLK_TCK */
211103729Swollman# endif /* _SC_CLK_TCK */
212103729Swollman#endif /* !BSDTIMES && POSIX */
213103729Swollman
214103729Swollman    settimes();			/* Immed. estab. timing base */
215103729Swollman#ifdef TESLA
216103729Swollman    do_logout = 0;
217103729Swollman#endif /* TESLA */
218103729Swollman
219103729Swollman    /*
220103729Swollman     * Make sure we have 0, 1, 2 open
221103729Swollman     * Otherwise `` jobs will not work... (From knaff@poly.polytechnique.fr)
222103729Swollman     */
223103729Swollman    {
224103729Swollman	do
225103729Swollman	    if ((f = xopen(_PATH_DEVNULL, O_RDONLY|O_LARGEFILE)) == -1 &&
226103729Swollman		(f = xopen("/", O_RDONLY|O_LARGEFILE)) == -1)
227103729Swollman		exit(1);
228103729Swollman	while (f < 3);
229103729Swollman	xclose(f);
230103729Swollman    }
231103729Swollman
232103729Swollman#ifdef O_TEXT
233103729Swollman    setmode(0, O_TEXT);
234103729Swollman#endif
235103729Swollman
236103729Swollman    osinit();			/* Os dependent initialization */
237103729Swollman
238103729Swollman
239103729Swollman    {
240103729Swollman	char *t;
241103729Swollman
242103729Swollman	t = strrchr(argv[0], '/');
243103729Swollman#ifdef WINNT_NATIVE
244103729Swollman	{
245103729Swollman	    char *s = strrchr(argv[0], '\\');
246103729Swollman	    if (s)
247103729Swollman		t = s;
248103729Swollman	}
249103729Swollman#endif /* WINNT_NATIVE */
250103729Swollman	t = t ? t + 1 : argv[0];
251103729Swollman	if (*t == '-') t++;
252103729Swollman	progname = strsave((t && *t) ? t : tcshstr);    /* never want a null */
253103729Swollman	tcsh = strcmp(progname, tcshstr) == 0;
254103729Swollman    }
255103729Swollman
256103729Swollman    /*
257103729Swollman     * Initialize non constant strings
258103729Swollman     */
259103729Swollman#ifdef _PATH_BSHELL
260103729Swollman    STR_BSHELL = SAVE(_PATH_BSHELL);
261103729Swollman#endif
262103729Swollman#ifdef _PATH_TCSHELL
263103729Swollman    STR_SHELLPATH = SAVE(_PATH_TCSHELL);
264103729Swollman#else
265103729Swollman# ifdef _PATH_CSHELL
266103729Swollman    STR_SHELLPATH = SAVE(_PATH_CSHELL);
267103729Swollman# endif
268103729Swollman#endif
269103729Swollman    STR_environ = blk2short(environ);
270103729Swollman    environ = short2blk(STR_environ);	/* So that we can free it */
271106055Swollman    STR_WORD_CHARS = SAVE(WORD_CHARS);
272106055Swollman
273106055Swollman    HIST = '!';
274103729Swollman    HISTSUB = '^';
275103729Swollman    PRCH = '>';
276103729Swollman    PRCHROOT = '#';
277103729Swollman    word_chars = STR_WORD_CHARS;
278103729Swollman    bslash_quote = 0;		/* PWP: do tcsh-style backslash quoting? */
279103729Swollman
280103729Swollman    /* Default history size to 100 */
281103729Swollman    setcopy(STRhistory, str2short("100"), VAR_READWRITE);
282103729Swollman
283103729Swollman    tempv = argv;
284103729Swollman    ffile = SAVE(tempv[0]);
285103729Swollman    dolzero = 0;
286103729Swollman    if (eq(ffile, STRaout))	/* A.out's are quittable */
287103729Swollman	quitit = 1;
288103729Swollman    uid = getuid();
289103729Swollman    gid = getgid();
290103729Swollman    euid = geteuid();
291103729Swollman    egid = getegid();
292103729Swollman    /*
293103729Swollman     * We are a login shell if: 1. we were invoked as -<something> with
294103729Swollman     * optional arguments 2. or we were invoked only with the -l flag
295103729Swollman     */
296103729Swollman    loginsh = (**tempv == '-') || (argc == 2 &&
297165230Spjd				   tempv[1][0] == '-' && tempv[1][1] == 'l' &&
298165230Spjd						tempv[1][2] == '\0');
299165230Spjd#ifdef _VMS_POSIX
300103729Swollman    /* No better way to find if we are a login shell */
301103729Swollman    if (!loginsh) {
302103729Swollman	loginsh = (argc == 1 && getppid() == 1);
303103729Swollman	**tempv = '-';	/* Avoid giving VMS an acidic stomach */
304103729Swollman    }
305103729Swollman#endif /* _VMS_POSIX */
306103729Swollman
307103729Swollman    if (loginsh && **tempv != '-') {
308103729Swollman	char *argv0;
309103729Swollman
310103729Swollman	/*
311103729Swollman	 * Mangle the argv space
312103729Swollman	 */
313103729Swollman	tempv[1][0] = '\0';
314103729Swollman	tempv[1][1] = '\0';
315103729Swollman	tempv[1] = NULL;
316103729Swollman	argv0 = strspl("-", *tempv);
317103729Swollman	*tempv = argv0;
318103729Swollman	argc--;
319103729Swollman    }
320103729Swollman    if (loginsh) {
3211539Srgrimes	(void) time(&chktim);
32298269Swollman	setNS(STRloginsh);
32393032Simp    }
32493032Simp
32593032Simp    AsciiOnly = 1;
32693032Simp    NoNLSRebind = getenv("NOREBIND") != NULL;
32793032Simp#ifdef NLS
32893032Simp# ifdef SETLOCALEBUG
32993032Simp    dont_free = 1;
33093032Simp# endif /* SETLOCALEBUG */
33193032Simp    (void) setlocale(LC_ALL, "");
33293032Simp# ifdef LC_COLLATE
33393032Simp    (void) setlocale(LC_COLLATE, "");
33493032Simp# endif
33593032Simp# ifdef SETLOCALEBUG
33693032Simp    dont_free = 0;
33793032Simp# endif /* SETLOCALEBUG */
33893032Simp# ifdef STRCOLLBUG
33993032Simp    fix_strcoll_bug();
34093032Simp# endif /* STRCOLLBUG */
34193032Simp
34293032Simp    {
34393032Simp	int     k;
34493032Simp
34593032Simp	for (k = 0200; k <= 0377 && !Isprint(CTL_ESC(k)); k++)
34693032Simp	    continue;
34793032Simp	AsciiOnly = MB_CUR_MAX == 1 && k > 0377;
34893032Simp    }
34993032Simp#else
35093032Simp    AsciiOnly = getenv("LANG") == NULL && getenv("LC_CTYPE") == NULL;
35193032Simp#endif				/* NLS */
35224896Sbde    if (MapsAreInited && !NLSMapsAreInited)
35324896Sbde	ed_InitNLSMaps();
35493032Simp    ResetArrowKeys();
35524896Sbde
35693032Simp    /*
35793032Simp     * Initialize for periodic command intervals. Also, initialize the dummy
35893032Simp     * tty list for login-watch.
35993032Simp     */
36093032Simp    (void) time(&t_period);
36193032Simp#ifndef HAVENOUTMP
36293032Simp    initwatch();
36393032Simp#endif /* !HAVENOUTMP */
36493032Simp
36593032Simp#if defined(alliant)
36693032Simp    /*
36793032Simp     * From:  Jim Pace <jdp@research.att.com>
36893032Simp     * tcsh does not work properly on the alliants through an rlogin session.
36993032Simp     * The shell generally hangs.  Also, reference to the controlling terminal
37093032Simp     * does not work ( ie: echo foo > /dev/tty ).
371146186Sdelphij     *
37293032Simp     * A security feature was added to rlogind affecting FX/80's Concentrix
37393032Simp     * from revision 5.5.xx upwards (through 5.7 where this fix was implemented)
3741539Srgrimes     * This security change also affects the FX/2800 series.
375100140Swollman     * The security change to rlogind requires the process group of an rlogin
376106812Smike     * session become disassociated with the tty in rlogind.
37798269Swollman     *
378126141Sache     * The changes needed are:
379126141Sache     * 1. set the process group
380100145Swollman     * 2. reenable the control terminal
381100145Swollman     */
382100145Swollman     if (loginsh && isatty(SHIN)) {
383100145Swollman	 ttyn = ttyname(SHIN);
384126141Sache	 xclose(SHIN);
38598269Swollman	 SHIN = xopen(ttyn, O_RDWR|O_LARGEFILE);
38698269Swollman	 shpgrp = getpid();
38798269Swollman	 (void) ioctl (SHIN, TIOCSPGRP, (ioctl_t) &shpgrp);
388106812Smike	 (void) setpgid(0, shpgrp);
389100140Swollman     }
390100140Swollman#endif /* alliant */
39198269Swollman
39298269Swollman    /*
39398269Swollman     * Move the descriptors to safe places. The variable didfds is 0 while we
39498269Swollman     * have only FSH* to work with. When didfds is true, we have 0,1,2 and
39598269Swollman     * prefer to use these.
39698269Swollman     */
39798269Swollman    initdesc();
39898269Swollman
399106812Smike    /*
40098269Swollman     * Get and set the tty now
401106812Smike     */
40298269Swollman    if ((ttyn = ttyname(SHIN)) != NULL) {
40398269Swollman	/*
40498269Swollman	 * Could use rindex to get rid of other possible path components, but
40598269Swollman	 * hpux preserves the subdirectory /pty/ when storing the tty name in
406106812Smike	 * utmp, so we keep it too.
407106812Smike	 */
408176607Sru	if (strncmp(ttyn, "/dev/", 5) == 0)
409106812Smike	    setv(STRtty, cp = SAVE(ttyn + 5), VAR_READWRITE);
41098269Swollman	else
411119141Swollman	    setv(STRtty, cp = SAVE(ttyn), VAR_READWRITE);
41298269Swollman    }
41398269Swollman    else
41498269Swollman	setv(STRtty, cp = SAVE(""), VAR_READWRITE);
41598269Swollman    /*
416100140Swollman     * Initialize the shell variables. ARGV and PROMPT are initialized later.
417100140Swollman     * STATUS is also munged in several places. CHILD is munged when
418100140Swollman     * forking/waiting
419103729Swollman     */
420100140Swollman
421100140Swollman    /*
422103012Stjr     * 7-10-87 Paul Placeway autologout should be set ONLY on login shells and
423100140Swollman     * on shells running as root.  Out of these, autologout should NOT be set
424100140Swollman     * for any psudo-terminals (this catches most window systems) and not for
42598269Swollman     * any terminal running X windows.
42698269Swollman     *
42798269Swollman     * At Ohio State, we have had problems with a user having his X session
42898269Swollman     * drop out from under him (on a Sun) because the shell in his master
42998269Swollman     * xterm timed out and exited.
43098269Swollman     *
431106812Smike     * Really, this should be done with a program external to the shell, that
43298269Swollman     * watches for no activity (and NO running programs, such as dump) on a
43398269Swollman     * terminal for a long peroid of time, and then SIGHUPS the shell on that
43498269Swollman     * terminal.
43598269Swollman     *
43698269Swollman     * bugfix by Rich Salz <rsalz@PINEAPPLE.BBN.COM>: For root rsh things
43798269Swollman     * allways first check to see if loginsh or really root, then do things
43898269Swollman     * with ttyname()
43998269Swollman     *
44098269Swollman     * Also by Jean-Francois Lamy <lamy%ai.toronto.edu@RELAY.CS.NET>: check the
44198269Swollman     * value of cp before using it! ("root can rsh too")
44298269Swollman     *
443138659Strhodes     * PWP: keep the nested ifs; the order of the tests matters and a good
444138659Strhodes     * (smart) C compiler might re-arange things wrong.
445138659Strhodes     */
446138659Strhodes#ifdef AUTOLOGOUT
447138659Strhodes# ifdef convex
448138659Strhodes    if (uid == 0)
44998269Swollman	/*  root always has a 15 minute autologout  */
450108381Smike	setcopy(STRautologout, STRrootdefautologout, VAR_READWRITE);
451108381Smike    else
45298269Swollman	if (loginsh)
45398269Swollman	    /*  users get autologout set to 0  */
45498269Swollman	    setcopy(STRautologout, STR0, VAR_READWRITE);
45598269Swollman# else /* convex */
45698269Swollman    if (loginsh || (uid == 0)) {
45798269Swollman	if (*cp) {
45898269Swollman	    /* only for login shells or root and we must have a tty */
45998269Swollman	    if ((cp2 = Strrchr(cp, (Char) '/')) != NULL) {
46098269Swollman		cp = cp2 + 1;
461106812Smike	    }
462106812Smike	    else
463106812Smike		cp2 = cp;
464106812Smike	    if (!(((Strncmp(cp2, STRtty, 3) == 0) && Isalpha(cp2[3])) ||
465106812Smike		  ((Strncmp(cp, STRpts, 3) == 0) && cp[3] == '/'))) {
466106812Smike		if (getenv("DISPLAY") == NULL) {
467106812Smike		    /* NOT on X window shells */
468106812Smike		    setcopy(STRautologout, STRdefautologout, VAR_READWRITE);
469106812Smike		}
47098269Swollman	    }
4711539Srgrimes	}
47293032Simp    }
47393032Simp# endif /* convex */
474106065Swollman#endif /* AUTOLOGOUT */
47598269Swollman
47693032Simp    sigset_interrupting(SIGALRM, queue_alrmcatch);
47793032Simp
47893032Simp    setcopy(STRstatus, STR0, VAR_READWRITE);
47993032Simp
48093032Simp    /*
48193032Simp     * get and set machine specific environment variables
482117105Sbde     */
483175220Sjhb    getmachine();
48493032Simp
48593032Simp
48693032Simp    /*
48793032Simp     * Publish the selected echo style
488183390Speter     */
48993032Simp#if ECHO_STYLE != BSD_ECHO
49093032Simp    if (tcsh) {
49193032Simp# if ECHO_STYLE == NONE_ECHO
49293032Simp	setcopy(STRecho_style, STRnone, VAR_READWRITE);
49393032Simp# endif /* ECHO_STYLE == NONE_ECHO */
49493032Simp# if ECHO_STYLE == SYSV_ECHO
49593032Simp	setcopy(STRecho_style, STRsysv, VAR_READWRITE);
49693032Simp# endif /* ECHO_STYLE == SYSV_ECHO */
49793032Simp# if ECHO_STYLE == BOTH_ECHO
498143952Sdas	setcopy(STRecho_style, STRboth, VAR_READWRITE);
49993032Simp# endif /* ECHO_STYLE == BOTH_ECHO */
500143952Sdas    } else
501143952Sdas#endif /* ECHO_STYLE != BSD_ECHO */
502103729Swollman	setcopy(STRecho_style, STRbsd, VAR_READWRITE);
50393032Simp
504103729Swollman    /*
505103729Swollman     * increment the shell level.
50693032Simp     */
507103729Swollman    shlvl(1);
50893032Simp
509103729Swollman    if ((tcp = getenv("HOME")) != NULL)
510103729Swollman	cp = quote(SAVE(tcp));
51193032Simp    else
51293032Simp	cp = NULL;
51393032Simp
51493032Simp    if (cp == NULL)
51593032Simp	fast = 1;		/* No home -> can't read scripts */
51693032Simp    else
51793032Simp	setv(STRhome, cp, VAR_READWRITE);
51893032Simp
51993032Simp    dinit(cp);			/* dinit thinks that HOME == cwd in a login
52093032Simp				 * shell */
52193032Simp    /*
52293032Simp     * Grab other useful things from the environment. Should we grab
52393032Simp     * everything??
52493032Simp     */
52593032Simp    {
52693032Simp	char *cln, *cus, *cgr;
527103867Smike	struct passwd *pw;
528103867Smike	struct group *gr;
529103867Smike
53093032Simp
531103867Smike#ifdef apollo
532103867Smike	int     oid = getoid();
53393032Simp
53493032Simp	setv(STRoid, Itoa(oid, 0, 0), VAR_READWRITE);
53593032Simp#endif /* apollo */
53693032Simp
537103729Swollman	setv(STRuid, Itoa(uid, 0, 0), VAR_READWRITE);
53893032Simp
539103729Swollman	setv(STRgid, Itoa(gid, 0, 0), VAR_READWRITE);
540103729Swollman
54193032Simp	cln = getenv("LOGNAME");
54293032Simp	cus = getenv("USER");
54393032Simp	if (cus != NULL)
54493032Simp	    setv(STRuser, quote(SAVE(cus)), VAR_READWRITE);
54593032Simp	else if (cln != NULL)
54693032Simp	    setv(STRuser, quote(SAVE(cln)), VAR_READWRITE);
54793032Simp	else if ((pw = xgetpwuid(uid)) == NULL)
54893032Simp	    setcopy(STRuser, str2short("unknown"), VAR_READWRITE);
54993032Simp	else
550107913Sdillon	    setcopy(STRuser, str2short(pw->pw_name), VAR_READWRITE);
55193032Simp	if (cln == NULL)
55293032Simp	    tsetenv(STRLOGNAME, varval(STRuser));
55393032Simp	if (cus == NULL)
55493032Simp	    tsetenv(STRKUSER, varval(STRuser));
55593032Simp
55693032Simp	cgr = getenv("GROUP");
55723657Speter	if (cgr != NULL)
558126142Sache	    setv(STRgroup, quote(SAVE(cgr)), VAR_READWRITE);
559126142Sache	else if ((gr = xgetgrgid(gid)) == NULL)
56042518Smsmith	    setcopy(STRgroup, str2short("unknown"), VAR_READWRITE);
561126142Sache	else
56298269Swollman	    setcopy(STRgroup, str2short(gr->gr_name), VAR_READWRITE);
563177791Skib	if (cgr == NULL)
564177791Skib	    tsetenv(STRKGROUP, varval(STRgroup));
565177830Skib    }
566177791Skib
567177791Skib    /*
568177791Skib     * HOST may be wrong, since rexd transports the entire environment on sun
569177791Skib     * 3.x Just set it again
570178064Skib     */
571177791Skib    {
572177791Skib	char    cbuff[MAXHOSTNAMELEN];
573177791Skib
5741539Srgrimes	if (gethostname(cbuff, sizeof(cbuff)) >= 0) {
5751539Srgrimes	    cbuff[sizeof(cbuff) - 1] = '\0';	/* just in case */
5761539Srgrimes	    tsetenv(STRHOST, str2short(cbuff));
577	}
578	else
579	    tsetenv(STRHOST, str2short("unknown"));
580    }
581
582
583#ifdef REMOTEHOST
584    /*
585     * Try to determine the remote host we were logged in from.
586     */
587    remotehost();
588#endif /* REMOTEHOST */
589
590#ifdef apollo
591    if ((tcp = getenv("SYSTYPE")) == NULL)
592	tcp = "bsd4.3";
593    tsetenv(STRSYSTYPE, quote(str2short(tcp)));
594#endif /* apollo */
595
596    /*
597     * set editing on by default, unless running under Emacs as an inferior
598     * shell.
599     * We try to do this intelligently. If $TERM is available, then it
600     * should determine if we should edit or not. $TERM is preserved
601     * across rlogin sessions, so we will not get confused if we rlogin
602     * under an emacs shell. Another advantage is that if we run an
603     * xterm under an emacs shell, then the $TERM will be set to
604     * xterm, so we are going to want to edit. Unfortunately emacs
605     * does not restore all the tty modes, so xterm is not very well
606     * set up. But this is not the shell's fault.
607     * Also don't edit if $TERM == wm, for when we're running under an ATK app.
608     * Finally, emacs compiled under terminfo, sets the terminal to dumb,
609     * so disable editing for that too.
610     *
611     * Unfortunately, in some cases the initial $TERM setting is "unknown",
612     * "dumb", or "network" which is then changed in the user's startup files.
613     * We fix this by setting noediting here if $TERM is unknown/dumb and
614     * if noediting is set, we switch on editing if $TERM is changed.
615     */
616    if ((tcp = getenv("TERM")) != NULL) {
617	setv(STRterm, quote(SAVE(tcp)), VAR_READWRITE);
618	noediting = strcmp(tcp, "unknown") == 0 || strcmp(tcp, "dumb") == 0 ||
619		    strcmp(tcp, "network") == 0;
620	editing = strcmp(tcp, "emacs") != 0 && strcmp(tcp, "wm") != 0 &&
621		  !noediting;
622    }
623    else {
624	noediting = 0;
625	editing = ((tcp = getenv("EMACS")) == NULL || strcmp(tcp, "t") != 0);
626    }
627
628    /*
629     * The 'edit' variable is either set or unset.  It doesn't
630     * need a value.  Making it 'emacs' might be confusing.
631     */
632    if (editing)
633	setNS(STRedit);
634
635
636    /*
637     * still more mutability: make the complete routine automatically add the
638     * suffix of file names...
639     */
640    setNS(STRaddsuffix);
641
642    /*
643     * Compatibility with tcsh >= 6.12 by default
644     */
645    setNS(STRcsubstnonl);
646
647    /*
648     * Random default kill ring size
649     */
650    setcopy(STRkillring, str2short("30"), VAR_READWRITE);
651
652    /*
653     * Re-initialize path if set in environment
654     */
655    if ((tcp = getenv("PATH")) == NULL)
656#ifdef _PATH_DEFPATH
657	importpath(str2short(_PATH_DEFPATH));
658#else /* !_PATH_DEFPATH */
659	setq(STRpath, defaultpath(), &shvhed, VAR_READWRITE);
660#endif /* _PATH_DEFPATH */
661    else
662	/* Importpath() allocates memory for the path, and the
663	 * returned pointer from SAVE() was discarded, so
664	 * this was a memory leak.. (sg)
665	 *
666	 * importpath(SAVE(tcp));
667	 */
668	importpath(str2short(tcp));
669
670
671    {
672	/* If the SHELL environment variable ends with "tcsh", set
673	 * STRshell to the same path.  This is to facilitate using
674	 * the executable in environments where the compiled-in
675	 * default isn't appropriate (sg).
676	 */
677
678	size_t sh_len = 0;
679
680	if ((tcp = getenv("SHELL")) != NULL) {
681	    sh_len = strlen(tcp);
682	    if ((sh_len >= 5 && strcmp(tcp + (sh_len - 5), "/tcsh") == 0) ||
683	        (!tcsh && sh_len >= 4 && strcmp(tcp + (sh_len - 4), "/csh") == 0))
684		setv(STRshell, quote(SAVE(tcp)), VAR_READWRITE);
685	    else
686		sh_len = 0;
687	}
688	if (sh_len == 0)
689	    setcopy(STRshell, STR_SHELLPATH, VAR_READWRITE);
690    }
691
692#ifdef _OSD_POSIX  /* BS2000 needs this variable set to "SHELL" */
693    if ((tcp = getenv("PROGRAM_ENVIRONMENT")) == NULL)
694	tcp = "SHELL";
695    tsetenv(STRPROGRAM_ENVIRONMENT, quote(str2short(tcp)));
696#endif /* _OSD_POSIX */
697
698#ifdef COLOR_LS_F
699    if ((tcp = getenv("LS_COLORS")) != NULL)
700	parseLS_COLORS(str2short(tcp));
701#endif /* COLOR_LS_F */
702
703    doldol = putn((int) getpid());	/* For $$ */
704#ifdef WINNT_NATIVE
705    {
706	char *tmp;
707	Char *tmp2;
708	if ((tmp = getenv("TMP")) != NULL) {
709	    tmp = xasprintf("%s/%s", tmp, "sh");
710	    tmp2 = SAVE(tmp);
711	xfree(tmp);
712    }
713	else {
714	    tmp2 = SAVE("");
715	}
716	shtemp = Strspl(tmp2, doldol);	/* For << */
717	xfree(tmp2);
718    }
719#else /* !WINNT_NATIVE */
720    shtemp = Strspl(STRtmpsh, doldol);	/* For << */
721#endif /* WINNT_NATIVE */
722
723    /*
724     * Record the interrupt states from the parent process. If the parent is
725     * non-interruptible our hand must be forced or we (and our children) won't
726     * be either. Our children inherit termination from our parent. We catch it
727     * only if we are the login shell.
728     */
729    sigaction(SIGINT, NULL, &parintr);
730    sigaction(SIGTERM, NULL, &parterm);
731
732
733#ifdef TCF
734    /* Enable process migration on ourselves and our progeny */
735    (void) signal(SIGMIGRATE, SIG_DFL);
736#endif /* TCF */
737
738    /*
739     * dspkanji/dspmbyte autosetting
740     */
741    /* PATCH IDEA FROM Issei.Suzuki VERY THANKS */
742#if defined(DSPMBYTE)
743#if defined(NLS) && defined(LC_CTYPE)
744    if (((tcp = setlocale(LC_CTYPE, NULL)) != NULL || (tcp = getenv("LANG")) != NULL) && !adrof(CHECK_MBYTEVAR)) {
745#else
746    if ((tcp = getenv("LANG")) != NULL && !adrof(CHECK_MBYTEVAR)) {
747#endif
748	autoset_dspmbyte(str2short(tcp));
749    }
750#if defined(WINNT_NATIVE)
751    else if (!adrof(CHECK_MBYTEVAR))
752      nt_autoset_dspmbyte();
753#endif /* WINNT_NATIVE */
754#endif
755
756    fix_version();		/* publish the shell version */
757
758    if (argc > 1 && strcmp(argv[1], "--version") == 0) {
759	xprintf("%S\n", varval(STRversion));
760	xexit(0);
761    }
762    if (argc > 1 && strcmp(argv[1], "--help") == 0) {
763	xprintf("%S\n\n", varval(STRversion));
764	xprintf(CGETS(11, 8, HELP_STRING));
765	xexit(0);
766    }
767    /*
768     * Process the arguments.
769     *
770     * Note that processing of -v/-x is actually delayed till after script
771     * processing.
772     *
773     * We set the first character of our name to be '-' if we are a shell
774     * running interruptible commands.  Many programs which examine ps'es
775     * use this to filter such shells out.
776     */
777    argc--, tempv++;
778    while (argc > 0 && (tcp = tempv[0])[0] == '-' &&
779	   *++tcp != '\0' && !batch) {
780	do
781	    switch (*tcp++) {
782
783	    case 0:		/* -	Interruptible, no prompt */
784		prompt = 0;
785		setintr = 1;
786		nofile = 1;
787		break;
788
789	    case 'b':		/* -b	Next arg is input file */
790		batch = 1;
791		break;
792
793	    case 'c':		/* -c	Command input from arg */
794		if (argc == 1)
795		    xexit(0);
796		argc--, tempv++;
797#ifdef M_XENIX
798		/* Xenix Vi bug:
799		   it relies on a 7 bit environment (/bin/sh), so it
800		   pass ascii arguments with the 8th bit set */
801		if (!strcmp(argv[0], "sh"))
802		  {
803		    char *p;
804
805		    for (p = tempv[0]; *p; ++p)
806		      *p &= ASCII;
807		  }
808#endif
809		arginp = SAVE(tempv[0]);
810
811		/*
812		 * we put the command into a variable
813		 */
814		if (arginp != NULL)
815		    setv(STRcommand, quote(Strsave(arginp)), VAR_READWRITE);
816
817		/*
818		 * * Give an error on -c arguments that end in * backslash to
819		 * ensure that you don't make * nonportable csh scripts.
820		 */
821		{
822		    int count;
823
824		    cp = Strend(arginp);
825		    count = 0;
826		    while (cp > arginp && *--cp == '\\')
827			++count;
828		    if ((count & 1) != 0) {
829			exiterr = 1;
830			stderror(ERR_ARGC);
831		    }
832		}
833		prompt = 0;
834		nofile = 1;
835		break;
836	    case 'd':		/* -d	Load directory stack from file */
837		rdirs = 1;
838		break;
839
840#ifdef apollo
841	    case 'D':		/* -D	Define environment variable */
842		{
843		    Char *dp;
844
845		    cp = str2short(tcp);
846		    if (dp = Strchr(cp, '=')) {
847			*dp++ = '\0';
848			tsetenv(cp, dp);
849		    }
850		    else
851			tsetenv(cp, STRNULL);
852		}
853		*tcp = '\0'; 	/* done with this argument */
854		break;
855#endif /* apollo */
856
857	    case 'e':		/* -e	Exit on any error */
858		exiterr = 1;
859		break;
860
861	    case 'f':		/* -f	Fast start */
862		fast = 1;
863		break;
864
865	    case 'i':		/* -i	Interactive, even if !intty */
866		intact = 1;
867		nofile = 1;
868		break;
869
870	    case 'm':		/* -m	read .cshrc (from su) */
871		mflag = 1;
872		break;
873
874	    case 'n':		/* -n	Don't execute */
875		noexec = 1;
876		break;
877
878	    case 'q':		/* -q	(Undoc'd) ... die on quit */
879		quitit = 1;
880		break;
881
882	    case 's':		/* -s	Read from std input */
883		nofile = 1;
884		break;
885
886	    case 't':		/* -t	Read one line from input */
887		onelflg = 2;
888		prompt = 0;
889		nofile = 1;
890		break;
891
892	    case 'v':		/* -v	Echo hist expanded input */
893		nverbose = 1;	/* ... later */
894		break;
895
896	    case 'x':		/* -x	Echo just before execution */
897		nexececho = 1;	/* ... later */
898		break;
899
900	    case 'V':		/* -V	Echo hist expanded input */
901		setNS(STRverbose);	/* NOW! */
902		break;
903
904	    case 'X':		/* -X	Echo just before execution */
905		setNS(STRecho);	/* NOW! */
906		break;
907
908	    case 'F':
909		/*
910		 * This will cause children to be created using fork instead of
911		 * vfork.
912		 */
913		use_fork = 1;
914		break;
915
916	    case ' ':
917	    case '\t':
918		/*
919		 * for O/S's that don't do the argument parsing right in
920		 * "#!/foo -f " scripts
921		 */
922		break;
923
924	    default:		/* Unknown command option */
925		exiterr = 1;
926		stderror(ERR_TCSHUSAGE, tcp-1, progname);
927		break;
928
929	} while (*tcp);
930	tempv++, argc--;
931    }
932
933    if (quitit)			/* With all due haste, for debugging */
934	(void) signal(SIGQUIT, SIG_DFL);
935
936    /*
937     * Unless prevented by -, -c, -i, -s, or -t, if there are remaining
938     * arguments the first of them is the name of a shell file from which to
939     * read commands.
940     */
941    if (nofile == 0 && argc > 0) {
942	nofile = xopen(tempv[0], O_RDONLY|O_LARGEFILE);
943	if (nofile < 0) {
944	    child = 1;		/* So this ... */
945	    /* ... doesn't return */
946	    stderror(ERR_SYSTEM, tempv[0], strerror(errno));
947	}
948#ifdef O_TEXT
949	setmode(nofile, O_TEXT);
950#endif
951	xfree(ffile);
952	dolzero = 1;
953	ffile = SAVE(tempv[0]);
954	/*
955	 * Replace FSHIN. Handle /dev/std{in,out,err} specially
956	 * since once they are closed we cannot open them again.
957	 * In that case we use our own saved descriptors
958	 */
959	if ((SHIN = dmove(nofile, FSHIN)) < 0)
960	    switch(nofile) {
961	    case 0:
962		SHIN = FSHIN;
963		break;
964	    case 1:
965		SHIN = FSHOUT;
966		break;
967	    case 2:
968		SHIN = FSHDIAG;
969		break;
970	    default:
971		stderror(ERR_SYSTEM, tempv[0], strerror(errno));
972		break;
973	    }
974	(void) close_on_exec(SHIN, 1);
975	prompt = 0;
976	 /* argc not used any more */ tempv++;
977    }
978
979    /*
980     * Call to closem() used to be part of initdesc(). Now called below where
981     * the script name argument has become stdin. Kernel may have used a file
982     * descriptor to hold the name of the script (setuid case) and this name
983     * mustn't be lost by closing the fd too soon.
984     */
985    closem();
986
987    /*
988     * Consider input a tty if it really is or we are interactive. but not for
989     * editing (christos)
990     */
991    if (!(intty = isatty(SHIN))) {
992	if (adrof(STRedit))
993	    unsetv(STRedit);
994	editing = 0;
995    }
996    intty |= intact;
997#ifndef convex
998    if (intty || (intact && isatty(SHOUT))) {
999	if (!batch && (uid != euid || gid != egid)) {
1000	    errno = EACCES;
1001	    child = 1;		/* So this ... */
1002	    /* ... doesn't return */
1003	    stderror(ERR_SYSTEM, progname, strerror(errno));
1004	}
1005    }
1006#endif /* convex */
1007    isoutatty = isatty(SHOUT);
1008    isdiagatty = isatty(SHDIAG);
1009    /*
1010     * Decide whether we should play with signals or not. If we are explicitly
1011     * told (via -i, or -) or we are a login shell (arg0 starts with -) or the
1012     * input and output are both the ttys("csh", or "csh</dev/ttyx>/dev/ttyx")
1013     * Note that in only the login shell is it likely that parent may have set
1014     * signals to be ignored
1015     */
1016    if (loginsh || intact || (intty && isatty(SHOUT)))
1017	setintr = 1;
1018    settell();
1019    /*
1020     * Save the remaining arguments in argv.
1021     */
1022    setq(STRargv, blk2short(tempv), &shvhed, VAR_READWRITE);
1023
1024    /*
1025     * Set up the prompt.
1026     */
1027    if (prompt) {
1028	if (tcsh)
1029	    setcopy(STRprompt, STRdeftcshprompt, VAR_READWRITE);
1030	else
1031	    setcopy(STRprompt, STRdefcshprompt, VAR_READWRITE);
1032	/* that's a meta-questionmark */
1033	setcopy(STRprompt2, STRmquestion, VAR_READWRITE);
1034	setcopy(STRprompt3, STRKCORRECT, VAR_READWRITE);
1035    }
1036
1037    /*
1038     * If we are an interactive shell, then start fiddling with the signals;
1039     * this is a tricky game.
1040     */
1041    shpgrp = mygetpgrp();
1042    opgrp = tpgrp = -1;
1043    if (setintr) {
1044	struct sigaction osig;
1045
1046	**argv = '-';
1047	if (!quitit)		/* Wary! */
1048	    (void) signal(SIGQUIT, SIG_IGN);
1049	pintr_disabled = 1;
1050	sigset_interrupting(SIGINT, queue_pintr);
1051	(void) signal(SIGTERM, SIG_IGN);
1052
1053	/*
1054	 * No reason I can see not to save history on all these events..
1055	 * Most usual occurrence is in a window system, where we're not a login
1056	 * shell, but might as well be... (sg)
1057	 * But there might be races when lots of shells exit together...
1058	 * [this is also incompatible].
1059	 * We have to be mre careful here. If the parent wants to
1060	 * ignore the signals then we leave them untouched...
1061	 * We also only setup the handlers for shells that are trully
1062	 * interactive.
1063	 */
1064	sigaction(SIGHUP, NULL, &osig);
1065	if (loginsh || osig.sa_handler != SIG_IGN)
1066	    /* exit processing on HUP */
1067	    sigset_interrupting(SIGHUP, queue_phup);
1068#ifdef SIGXCPU
1069	sigaction(SIGXCPU, NULL, &osig);
1070	if (loginsh || osig.sa_handler != SIG_IGN)
1071	    /* exit processing on XCPU */
1072	    sigset_interrupting(SIGXCPU, queue_phup);
1073#endif
1074#ifdef SIGXFSZ
1075	sigaction(SIGXFSZ, NULL, &osig);
1076	if (loginsh || osig.sa_handler != SIG_IGN)
1077	    /* exit processing on XFSZ */
1078	    sigset_interrupting(SIGXFSZ, queue_phup);
1079#endif
1080
1081	if (quitit == 0 && arginp == 0) {
1082#ifdef SIGTSTP
1083	    (void) signal(SIGTSTP, SIG_IGN);
1084#endif
1085#ifdef SIGTTIN
1086	    (void) signal(SIGTTIN, SIG_IGN);
1087#endif
1088#ifdef SIGTTOU
1089	    (void) signal(SIGTTOU, SIG_IGN);
1090#endif
1091	    /*
1092	     * Wait till in foreground, in case someone stupidly runs csh &
1093	     * dont want to try to grab away the tty.
1094	     */
1095	    if (isatty(FSHDIAG))
1096		f = FSHDIAG;
1097	    else if (isatty(FSHOUT))
1098		f = FSHOUT;
1099	    else if (isatty(OLDSTD))
1100		f = OLDSTD;
1101	    else
1102		f = -1;
1103
1104#ifdef NeXT
1105	    /* NeXT 2.0 /usr/etc/rlogind, does not set our process group! */
1106	    if (shpgrp == 0) {
1107	        shpgrp = getpid();
1108		(void) setpgid(0, shpgrp);
1109	        (void) tcsetpgrp(f, shpgrp);
1110	    }
1111#endif /* NeXT */
1112#ifdef BSDJOBS			/* if we have tty job control */
1113    retry:
1114	    if ((tpgrp = tcgetpgrp(f)) != -1) {
1115		if (tpgrp != shpgrp) {
1116		    struct sigaction old;
1117
1118		    sigaction(SIGTTIN, NULL, &old);
1119		    signal(SIGTTIN, SIG_DFL);
1120		    (void) kill(0, SIGTTIN);
1121		    sigaction(SIGTTIN, &old, NULL);
1122		    goto retry;
1123		}
1124		/*
1125		 * Thanks to Matt Day for the POSIX references, and to
1126		 * Paul Close for the SGI clarification.
1127		 */
1128		if (setdisc(f) != -1) {
1129		    opgrp = shpgrp;
1130		    shpgrp = getpid();
1131		    tpgrp = shpgrp;
1132		    if (tcsetpgrp(f, shpgrp) == -1) {
1133			/*
1134			 * On hpux 7.03 this fails with EPERM. This happens on
1135			 * the 800 when opgrp != shpgrp at this point. (we were
1136			 * forked from a non job control shell)
1137			 * POSIX 7.2.4, says we failed because the process
1138			 * group specified did not belong to a process
1139			 * in the same session with the tty. So we set our
1140			 * process group and try again.
1141			 */
1142			if (setpgid(0, shpgrp) == -1) {
1143			    xprintf("setpgid:");
1144			    goto notty;
1145			}
1146			if (tcsetpgrp(f, shpgrp) == -1) {
1147			    xprintf("tcsetpgrp:");
1148			    goto notty;
1149			}
1150		    }
1151		    /*
1152		     * We check the process group now. If it is the same, then
1153		     * we don't need to set it again. On hpux 7.0 on the 300's
1154		     * if we set it again it fails with EPERM. This is the
1155		     * correct behavior according to POSIX 4.3.3 if the process
1156		     * was a session leader .
1157		     */
1158		    else if (shpgrp != mygetpgrp()) {
1159			if(setpgid(0, shpgrp) == -1) {
1160			    xprintf("setpgid:");
1161			    goto notty;
1162			}
1163		    }
1164#ifdef IRIS4D
1165		    /*
1166		     * But on irix 3.3 we need to set it again, even if it is
1167		     * the same. We do that to tell the system that we
1168		     * need BSD process group compatibility.
1169		     */
1170		    else
1171			(void) setpgid(0, shpgrp);
1172#endif
1173		    (void) close_on_exec(dcopy(f, FSHTTY), 1);
1174		}
1175		else
1176		    tpgrp = -1;
1177	    }
1178	    if (tpgrp == -1) {
1179	notty:
1180	        xprintf(CGETS(11, 1, "Warning: no access to tty (%s).\n"),
1181			strerror(errno));
1182		xprintf(CGETS(11, 2, "Thus no job control in this shell.\n"));
1183		/*
1184		 * Fix from:Sakari Jalovaara <sja@sirius.hut.fi> if we don't
1185		 * have access to tty, disable editing too
1186		 */
1187		if (adrof(STRedit))
1188		    unsetv(STRedit);
1189		editing = 0;
1190	    }
1191#else	/* BSDJOBS */		/* don't have job control, so frotz it */
1192	    tpgrp = -1;
1193#endif				/* BSDJOBS */
1194	}
1195    }
1196    if (setintr == 0 && parintr.sa_handler == SIG_DFL)
1197	setintr = 1;
1198
1199/*
1200 * SVR4 doesn't send a SIGCHLD when a child is stopped or continued if the
1201 * handler is installed with signal(2) or sigset(2).  sigaction(2) must
1202 * be used instead.
1203 *
1204 * David Dawes (dawes@physics.su.oz.au) Sept 1991
1205 */
1206    sigset_interrupting(SIGCHLD, queue_pchild);
1207
1208    if (intty && !arginp)
1209	(void) ed_Setup(editing);/* Get the tty state, and set defaults */
1210				 /* Only alter the tty state if editing */
1211
1212    /*
1213     * Set an exit here in case of an interrupt or error reading the shell
1214     * start-up scripts.
1215     */
1216    osetintr = setintr;
1217    oparintr = parintr;
1218    (void)cleanup_push_mark(); /* There is no outer handler */
1219    if (setexit() != 0) /* PWP */
1220	reenter = 1;
1221    else
1222	reenter = 0;
1223    exitset++;
1224    haderr = 0;			/* In case second time through */
1225    if (!fast && reenter == 0) {
1226	/* Will have varval(STRhome) here because set fast if don't */
1227	{
1228	    pintr_disabled++;
1229	    cleanup_push(&pintr_disabled, disabled_cleanup);
1230	    setintr = 0;/*FIXRESET:cleanup*/
1231	    /* onintr in /etc/ files has no effect */
1232	    parintr.sa_handler = SIG_IGN;/*FIXRESET: cleanup*/
1233#ifdef LOGINFIRST
1234#ifdef _PATH_DOTLOGIN
1235	    if (loginsh)
1236		(void) srcfile(_PATH_DOTLOGIN, 0, 0, NULL);
1237#endif
1238#endif
1239
1240#ifdef _PATH_DOTCSHRC
1241	    (void) srcfile(_PATH_DOTCSHRC, 0, 0, NULL);
1242#endif
1243	    if (!arginp && !onelflg && !havhash)
1244		dohash(NULL,NULL);
1245#ifndef LOGINFIRST
1246#ifdef _PATH_DOTLOGIN
1247	    if (loginsh)
1248		(void) srcfile(_PATH_DOTLOGIN, 0, 0, NULL);
1249#endif
1250#endif
1251	    cleanup_until(&pintr_disabled);
1252	    setintr = osetintr;
1253	    parintr = oparintr;
1254	}
1255#ifdef LOGINFIRST
1256	if (loginsh)
1257	    (void) srccat(varval(STRhome), STRsldotlogin);
1258#endif
1259	/* upward compat. */
1260	if (!srccat(varval(STRhome), STRsldottcshrc))
1261	    (void) srccat(varval(STRhome), STRsldotcshrc);
1262
1263	if (!arginp && !onelflg && !havhash)
1264	    dohash(NULL,NULL);
1265
1266	/*
1267	 * Source history before .login so that it is available in .login
1268	 */
1269	loadhist(NULL, 0);
1270#ifndef LOGINFIRST
1271	if (loginsh)
1272	    (void) srccat(varval(STRhome), STRsldotlogin);
1273#endif
1274	if (loginsh || rdirs)
1275	    loaddirs(NULL);
1276    }
1277    /* Reset interrupt flag */
1278    setintr = osetintr;
1279    parintr = oparintr;
1280    exitset--;
1281
1282    /* Initing AFTER .cshrc is the Right Way */
1283    if (intty && !arginp) {	/* PWP setup stuff */
1284	ed_Init();		/* init the new line editor */
1285#ifdef SIG_WINDOW
1286	check_window_size(1);	/* mung environment */
1287#endif				/* SIG_WINDOW */
1288    }
1289
1290    /*
1291     * Now are ready for the -v and -x flags
1292     */
1293    if (nverbose)
1294	setNS(STRverbose);
1295    if (nexececho)
1296	setNS(STRecho);
1297
1298    /*
1299     * All the rest of the world is inside this call. The argument to process
1300     * indicates whether it should catch "error unwinds".  Thus if we are a
1301     * interactive shell our call here will never return by being blown past on
1302     * an error.
1303     */
1304    process(setintr);
1305
1306    /*
1307     * Mop-up.
1308     */
1309    if (intty) {
1310	if (loginsh) {
1311	    xprintf("logout\n");
1312	    xclose(SHIN);
1313	    child = 1;
1314#ifdef TESLA
1315	    do_logout = 1;
1316#endif				/* TESLA */
1317	    goodbye(NULL, NULL);
1318	}
1319	else {
1320	    xprintf("exit\n");
1321	}
1322    }
1323    record();
1324    exitstat();
1325    return (0);
1326}
1327
1328void
1329untty(void)
1330{
1331#ifdef BSDJOBS
1332    if (tpgrp > 0 && opgrp != shpgrp) {
1333	(void) setpgid(0, opgrp);
1334	(void) tcsetpgrp(FSHTTY, opgrp);
1335	(void) resetdisc(FSHTTY);
1336    }
1337#endif /* BSDJOBS */
1338}
1339
1340void
1341importpath(Char *cp)
1342{
1343    size_t i = 0;
1344    Char *dp;
1345    Char **pv;
1346    int     c;
1347
1348    for (dp = cp; *dp; dp++)
1349	if (*dp == PATHSEP)
1350	    i++;
1351    /*
1352     * i+2 where i is the number of colons in the path. There are i+1
1353     * directories in the path plus we need room for a zero terminator.
1354     */
1355    pv = xcalloc(i + 2, sizeof(Char *));
1356    dp = cp;
1357    i = 0;
1358    if (*dp)
1359	for (;;) {
1360	    if ((c = *dp) == PATHSEP || c == 0) {
1361		*dp = 0;
1362		pv[i++] = Strsave(*cp ? cp : STRdot);
1363		if (c) {
1364		    cp = dp + 1;
1365		    *dp = PATHSEP;
1366		}
1367		else
1368		    break;
1369	    }
1370#ifdef WINNT_NATIVE
1371	    else if (*dp == '\\')
1372		*dp = '/';
1373#endif /* WINNT_NATIVE */
1374	    dp++;
1375	}
1376    pv[i] = 0;
1377    cleanup_push(pv, blk_cleanup);
1378    setq(STRpath, pv, &shvhed, VAR_READWRITE);
1379    cleanup_ignore(pv);
1380    cleanup_until(pv);
1381}
1382
1383/*
1384 * Source to the file which is the catenation of the argument names.
1385 */
1386static int
1387srccat(Char *cp, Char *dp)
1388{
1389    if (cp[0] == '/' && cp[1] == '\0')
1390	return srcfile(short2str(dp), (mflag ? 0 : 1), 0, NULL);
1391    else {
1392	Char *ep;
1393	char   *ptr;
1394	int rv;
1395
1396#ifdef WINNT_NATIVE
1397	ep = Strend(cp);
1398	if (ep != cp && ep[-1] == '/' && dp[0] == '/') /* silly win95 */
1399	    dp++;
1400#endif /* WINNT_NATIVE */
1401
1402	ep = Strspl(cp, dp);
1403	cleanup_push(ep, xfree);
1404	ptr = short2str(ep);
1405
1406	rv = srcfile(ptr, (mflag ? 0 : 1), 0, NULL);
1407	cleanup_until(ep);
1408	return rv;
1409    }
1410}
1411
1412/*
1413 * Source to a file putting the file descriptor in a safe place (> 2).
1414 */
1415#ifndef WINNT_NATIVE
1416static int
1417#else
1418int
1419#endif /*WINNT_NATIVE*/
1420srcfile(const char *f, int onlyown, int flag, Char **av)
1421{
1422    int unit;
1423
1424    if ((unit = xopen(f, O_RDONLY|O_LARGEFILE)) == -1)
1425	return 0;
1426#ifdef O_TEXT
1427    setmode(unit, O_TEXT);
1428#endif
1429    cleanup_push(&unit, open_cleanup);
1430    unit = dmove(unit, -1);
1431    cleanup_ignore(&unit);
1432    cleanup_until(&unit);
1433
1434    (void) close_on_exec(unit, 1);
1435    srcunit(unit, onlyown, flag, av);
1436    return 1;
1437}
1438
1439
1440/*
1441 * Save the shell state, and establish new argument vector, and new input
1442 * fd.
1443 */
1444static void
1445st_save(struct saved_state *st, int unit, int hflg, Char **al, Char **av)
1446{
1447    st->insource	= insource;
1448    st->SHIN		= SHIN;
1449    /* Want to preserve the meaning of "source file >output".
1450     * Save old descriptors, move new 0,1,2 to safe places and assign
1451     * them to SH* and let process() redo 0,1,2 from them.
1452     *
1453     * The macro returns true if d1 and d2 are good and they point to
1454     * different things.  If you don't avoid saving duplicate
1455     * descriptors, you really limit the depth of "source" recursion
1456     * you can do because of all the open file descriptors.  -IAN!
1457     */
1458#define NEED_SAVE_FD(d1,d2) \
1459    (fstat(d1, &s1) != -1 && fstat(d2, &s2) != -1 \
1460	&& (s1.st_ino != s2.st_ino || s1.st_dev != s2.st_dev) )
1461
1462    st->OLDSTD = st->SHOUT = st->SHDIAG = -1;/* test later to restore these */
1463    if (didfds) {
1464	    struct stat s1, s2;
1465	    if (NEED_SAVE_FD(0,OLDSTD)) {
1466		    st->OLDSTD = OLDSTD;
1467		    OLDSTD = dmove(0, -1);
1468		    (void)close_on_exec(OLDSTD, 1);
1469	    }
1470	    if (NEED_SAVE_FD(1,SHOUT)) {
1471		    st->SHOUT = SHOUT;
1472		    SHOUT = dmove(1, -1);
1473		    (void)close_on_exec(SHOUT, 1);
1474	    }
1475	    if (NEED_SAVE_FD(2,SHDIAG)) {
1476		    st->SHDIAG = SHDIAG;
1477		    SHDIAG = dmove(2, -1);
1478		    (void)close_on_exec(SHDIAG, 1);
1479	    }
1480	    donefds();
1481    }
1482
1483    st->intty		= intty;
1484    st->whyles		= whyles;
1485    st->gointr		= gointr;
1486    st->arginp		= arginp;
1487    st->evalp		= evalp;
1488    st->evalvec		= evalvec;
1489    st->alvecp		= alvecp;
1490    st->alvec		= alvec;
1491    st->onelflg		= onelflg;
1492    st->enterhist	= enterhist;
1493    if (hflg)
1494	st->HIST	= HIST;
1495    else
1496	st->HIST	= '\0';
1497    st->cantell		= cantell;
1498    cpybin(st->B, B);
1499
1500    /*
1501     * we can now pass arguments to source.
1502     * For compatibility we do that only if arguments were really
1503     * passed, otherwise we keep the old, global $argv like before.
1504     */
1505    if (av != NULL && *av != NULL) {
1506	struct varent *vp;
1507	if ((vp = adrof(STRargv)) != NULL && vp->vec != NULL)
1508	    st->argv = saveblk(vp->vec);
1509	else
1510	    st->argv = NULL;
1511	setq(STRargv, saveblk(av), &shvhed, VAR_READWRITE);
1512    }
1513    else
1514	st->argv = NULL;
1515    st->av = av;
1516
1517    SHIN	= unit;	/* Do this first */
1518
1519    /* Establish new input arena */
1520    {
1521	fbuf = NULL;
1522	fseekp = feobp = fblocks = 0;
1523	settell();
1524    }
1525
1526    arginp	= 0;
1527    onelflg	= 0;
1528    intty	= isatty(SHIN);
1529    whyles	= 0;
1530    gointr	= 0;
1531    evalvec	= 0;
1532    evalp	= 0;
1533    alvec	= al;
1534    alvecp	= 0;
1535    enterhist	= hflg;
1536    if (enterhist)
1537	HIST	= '\0';
1538    insource	= 1;
1539}
1540
1541
1542/*
1543 * Restore the shell to a saved state
1544 */
1545static void
1546st_restore(void *xst)
1547{
1548    struct saved_state *st;
1549
1550    st = xst;
1551    if (st->SHIN == -1)
1552	return;
1553
1554    /* Reset input arena */
1555    {
1556	int i;
1557	Char** nfbuf = fbuf;
1558	int nfblocks = fblocks;
1559
1560	fblocks = 0;
1561	fbuf = NULL;
1562	for (i = 0; i < nfblocks; i++)
1563	    xfree(nfbuf[i]);
1564	xfree(nfbuf);
1565    }
1566    cpybin(B, st->B);
1567
1568    xclose(SHIN);
1569
1570    insource	= st->insource;
1571    SHIN	= st->SHIN;
1572    if (st->OLDSTD != -1)
1573	xclose(OLDSTD), OLDSTD = st->OLDSTD;
1574    if (st->SHOUT != -1)
1575	xclose(SHOUT),  SHOUT = st->SHOUT;
1576    if (st->SHDIAG != -1)
1577	xclose(SHDIAG), SHDIAG = st->SHDIAG;
1578    arginp	= st->arginp;
1579    onelflg	= st->onelflg;
1580    evalp	= st->evalp;
1581    evalvec	= st->evalvec;
1582    alvecp	= st->alvecp;
1583    alvec	= st->alvec;
1584    intty	= st->intty;
1585    whyles	= st->whyles;
1586    gointr	= st->gointr;
1587    if (st->HIST != '\0')
1588	HIST	= st->HIST;
1589    enterhist	= st->enterhist;
1590    cantell	= st->cantell;
1591
1592    if (st->argv != NULL)
1593	setq(STRargv, st->argv, &shvhed, VAR_READWRITE);
1594    else if (st->av != NULL  && *st->av != NULL && adrof(STRargv) != NULL)
1595	unsetv(STRargv);
1596}
1597
1598/*
1599 * Source to a unit.  If onlyown it must be our file or our group or
1600 * we don't chance it.	This occurs on ".cshrc"s and the like.
1601 */
1602static void
1603srcunit(int unit, int onlyown, int hflg, Char **av)
1604{
1605    struct saved_state st;
1606
1607    st.SHIN = -1;	/* st_restore checks this */
1608
1609    if (unit < 0)
1610	return;
1611
1612    if (onlyown) {
1613	struct stat stb;
1614
1615	if (fstat(unit, &stb) < 0) {
1616	    xclose(unit);
1617	    return;
1618	}
1619    }
1620
1621    /* Does nothing before st_save() because st.SHIN == -1 */
1622    cleanup_push(&st, st_restore);
1623    if (setintr) {
1624	pintr_disabled++;
1625	cleanup_push(&pintr_disabled, disabled_cleanup);
1626    }
1627
1628    /* Save the current state and move us to a new state */
1629    st_save(&st, unit, hflg, NULL, av);
1630
1631    /*
1632     * Now if we are allowing commands to be interrupted, we let ourselves be
1633     * interrupted.
1634     */
1635    if (setintr) {
1636	cleanup_until(&pintr_disabled);
1637	pintr_disabled++;
1638	cleanup_push(&pintr_disabled, disabled_cleanup);
1639    }
1640
1641    process(0);		/* 0 -> blow away on errors */
1642
1643    /* Restore the old state */
1644    cleanup_until(&st);
1645}
1646
1647
1648/*ARGSUSED*/
1649void
1650goodbye(Char **v, struct command *c)
1651{
1652    USE(v);
1653    USE(c);
1654    record();
1655
1656    if (loginsh) {
1657	size_t omark;
1658	sigset_t set;
1659
1660	signal(SIGQUIT, SIG_IGN);
1661	sigaddset(&set, SIGQUIT);
1662	sigprocmask(SIG_UNBLOCK, &set, NULL);
1663	signal(SIGINT, SIG_IGN);
1664	sigaddset(&set, SIGINT);
1665	signal(SIGTERM, SIG_IGN);
1666	sigaddset(&set, SIGTERM);
1667	signal(SIGHUP, SIG_IGN);
1668	sigaddset(&set, SIGHUP);
1669	sigprocmask(SIG_UNBLOCK, &set, NULL);
1670	phup_disabled = 1;
1671	setintr = 0;		/* No interrupts after "logout" */
1672	/* Trap errors inside .logout */
1673	omark = cleanup_push_mark();
1674	if (setexit() == 0) {
1675	    if (!(adrof(STRlogout)))
1676		setcopy(STRlogout, STRnormal, VAR_READWRITE);
1677#ifdef _PATH_DOTLOGOUT
1678	    (void) srcfile(_PATH_DOTLOGOUT, 0, 0, NULL);
1679#endif
1680	    if (adrof(STRhome))
1681		(void) srccat(varval(STRhome), STRsldtlogout);
1682#ifdef TESLA
1683	    do_logout = 1;
1684#endif /* TESLA */
1685	}
1686	cleanup_pop_mark(omark);
1687    }
1688    exitstat();
1689}
1690
1691void
1692exitstat(void)
1693{
1694#ifdef PROF
1695    monitor(0);
1696#endif
1697    /*
1698     * Note that if STATUS is corrupted (i.e. getn bombs) then error will exit
1699     * directly because we poke child here. Otherwise we might continue
1700     * unwarrantedly (sic).
1701     */
1702    child = 1;
1703
1704    xexit(getn(varval(STRstatus)));
1705}
1706
1707/*
1708 * in the event of a HUP we want to save the history
1709 */
1710void
1711phup(void)
1712{
1713    if (loginsh) {
1714	setcopy(STRlogout, STRhangup, VAR_READWRITE);
1715#ifdef _PATH_DOTLOGOUT
1716	(void) srcfile(_PATH_DOTLOGOUT, 0, 0, NULL);
1717#endif
1718	if (adrof(STRhome))
1719	    (void) srccat(varval(STRhome), STRsldtlogout);
1720    }
1721
1722    record();
1723
1724#ifdef POSIXJOBS
1725    /*
1726     * We kill the last foreground process group. It then becomes
1727     * responsible to propagate the SIGHUP to its progeny.
1728     */
1729    {
1730	struct process *pp, *np;
1731
1732	for (pp = proclist.p_next; pp; pp = pp->p_next) {
1733	    np = pp;
1734	    /*
1735	     * Find if this job is in the foreground. It could be that
1736	     * the process leader has exited and the foreground flag
1737	     * is cleared for it.
1738	     */
1739	    do
1740		/*
1741		 * If a process is in the foreground we try to kill
1742		 * it's process group. If we succeed, then the
1743		 * whole job is gone. Otherwise we keep going...
1744		 * But avoid sending HUP to the shell again.
1745		 */
1746		if (((np->p_flags & PFOREGND) != 0) && np->p_jobid != shpgrp) {
1747		    np->p_flags &= ~PHUP;
1748		    if (killpg(np->p_jobid, SIGHUP) != -1) {
1749			/* In case the job was suspended... */
1750#ifdef SIGCONT
1751			(void) killpg(np->p_jobid, SIGCONT);
1752#endif
1753			break;
1754		    }
1755		}
1756	    while ((np = np->p_friends) != pp);
1757	}
1758    }
1759#endif /* POSIXJOBS */
1760
1761    xexit(SIGHUP);
1762}
1763
1764static Char   *jobargv[2] = {STRjobs, 0};
1765
1766/*
1767 * Catch an interrupt, e.g. during lexical input.
1768 * If we are an interactive shell, we reset the interrupt catch
1769 * immediately.  In any case we drain the shell output,
1770 * and finally go through the normal error mechanism, which
1771 * gets a chance to make the shell go away.
1772 */
1773int just_signaled;		/* bugfix by Michael Bloom (mg@ttidca.TTI.COM) */
1774
1775void
1776pintr(void)
1777{
1778    just_signaled = 1;
1779    pintr1(1);
1780}
1781
1782void
1783pintr1(int wantnl)
1784{
1785    if (setintr) {
1786	if (pjobs) {
1787	    pjobs = 0;
1788	    xputchar('\n');
1789	    dojobs(jobargv, NULL);
1790	    stderror(ERR_NAME | ERR_INTR);
1791	}
1792    }
1793    /* MH - handle interrupted completions specially */
1794    {
1795	if (InsideCompletion)
1796	    stderror(ERR_SILENT);
1797    }
1798    /* JV - Make sure we shut off inputl */
1799    {
1800	(void) Cookedmode();
1801	GettingInput = 0;
1802    }
1803    drainoline();
1804#ifdef HAVE_GETPWENT
1805    (void) endpwent();
1806#endif
1807
1808    /*
1809     * If we have an active "onintr" then we search for the label. Note that if
1810     * one does "onintr -" then we shan't be interruptible so we needn't worry
1811     * about that here.
1812     */
1813    if (gointr) {
1814	gotolab(gointr);
1815	reset();
1816    }
1817    else if (intty && wantnl) {
1818	if (editing) {
1819	    /*
1820	     * If we are editing a multi-line input command, and move to
1821	     * the beginning of the line, we don't want to trash it when
1822	     * we hit ^C
1823	     */
1824	    PastBottom();
1825	    ClearLines();
1826	    ClearDisp();
1827	}
1828	else {
1829	    /* xputchar('\n'); *//* Some like this, others don't */
1830	    (void) putraw('\r');
1831	    (void) putraw('\n');
1832	}
1833    }
1834    stderror(ERR_SILENT);
1835}
1836
1837/*
1838 * Process is the main driving routine for the shell.
1839 * It runs all command processing, except for those within { ... }
1840 * in expressions (which is run by a routine evalav in sh.exp.c which
1841 * is a stripped down process), and `...` evaluation which is run
1842 * also by a subset of this code in sh.glob.c in the routine backeval.
1843 *
1844 * The code here is a little strange because part of it is interruptible
1845 * and hence freeing of structures appears to occur when none is necessary
1846 * if this is ignored.
1847 *
1848 * Note that if catch is not set then we will unwind on any error.
1849 * If an end-of-file occurs, we return.
1850 */
1851void
1852process(int catch)
1853{
1854    jmp_buf_t osetexit;
1855    /* PWP: This might get nuked my longjmp so don't make it a register var */
1856    size_t omark;
1857
1858    getexit(osetexit);
1859    omark = cleanup_push_mark();
1860    exitset++;
1861    for (;;) {
1862	struct command *t;
1863	int hadhist, old_pintr_disabled;
1864
1865	(void) setexit();
1866	pendjob();
1867
1868	justpr = enterhist;	/* execute if not entering history */
1869
1870	if (haderr) {
1871	    if (!catch) {
1872		/* unwind */
1873		doneinp = 0;
1874		cleanup_pop_mark(omark);
1875		resexit(osetexit);
1876		reset();
1877	    }
1878	    haderr = 0;
1879	    /*
1880	     * Every error is eventually caught here or the shell dies.  It is
1881	     * at this point that we clean up any left-over open files, by
1882	     * closing all but a fixed number of pre-defined files.  Thus
1883	     * routines don't have to worry about leaving files open due to
1884	     * deeper errors... they will get closed here.
1885	     */
1886	    closem();
1887	    continue;
1888	}
1889	if (doneinp) {
1890	    doneinp = 0;
1891	    break;
1892	}
1893	if (chkstop)
1894	    chkstop--;
1895	if (neednote)
1896	    pnote();
1897	if (intty && prompt && evalvec == 0) {
1898	    just_signaled = 0;
1899	    mailchk();
1900	    /*
1901	     * Watch for logins/logouts. Next is scheduled commands stored
1902	     * previously using "sched." Then execute periodic commands.
1903	     * Following that, the prompt precmd is run.
1904	     */
1905#ifndef HAVENOUTMP
1906	    watch_login(0);
1907#endif /* !HAVENOUTMP */
1908	    sched_run();
1909	    period_cmd();
1910	    precmd();
1911	    /*
1912	     * If we are at the end of the input buffer then we are going to
1913	     * read fresh stuff. Otherwise, we are rereading input and don't
1914	     * need or want to prompt.
1915	     */
1916	    if (fseekp == feobp && aret == TCSH_F_SEEK)
1917		printprompt(0, NULL);
1918	    flush();
1919	    setalarm(1);
1920	}
1921	if (seterr) {
1922	    xfree(seterr);
1923	    seterr = NULL;
1924	}
1925
1926	/*
1927	 * Interruptible during interactive reads
1928	 */
1929	if (setintr)
1930	    pintr_push_enable(&old_pintr_disabled);
1931	hadhist = lex(&paraml);
1932	if (setintr)
1933	    cleanup_until(&old_pintr_disabled);
1934	cleanup_push(&paraml, lex_cleanup);
1935
1936	/*
1937	 * Echo not only on VERBOSE, but also with history expansion. If there
1938	 * is a lexical error then we forego history echo.
1939	 */
1940	if ((hadhist && !seterr && intty && !tellwhat && !Expand && !whyles) ||
1941	    adrof(STRverbose)) {
1942	    int odidfds = didfds;
1943	    haderr = 1;
1944	    didfds = 0;
1945	    prlex(&paraml);
1946	    flush();
1947	    haderr = 0;
1948	    didfds = odidfds;
1949	}
1950	(void) alarm(0);	/* Autologout OFF */
1951	alrmcatch_disabled = 1;
1952
1953	/*
1954	 * Save input text on the history list if reading in old history, or it
1955	 * is from the terminal at the top level and not in a loop.
1956	 *
1957	 * PWP: entry of items in the history list while in a while loop is done
1958	 * elsewhere...
1959	 */
1960	if (enterhist || (catch && intty && !whyles && !tellwhat && !arun))
1961	    savehist(&paraml, enterhist > 1);
1962
1963	if (Expand && seterr)
1964	    Expand = 0;
1965
1966	/*
1967	 * Print lexical error messages, except when sourcing history lists.
1968	 */
1969	if (!enterhist && seterr)
1970	    stderror(ERR_OLD);
1971
1972	/*
1973	 * If had a history command :p modifier then this is as far as we
1974	 * should go
1975	 */
1976	if (justpr)
1977	    goto cmd_done;
1978
1979	/*
1980	 * If had a tellwhat from twenex() then do
1981	 */
1982	if (tellwhat) {
1983	    (void) tellmewhat(&paraml, NULL);
1984	    goto cmd_done;
1985	}
1986
1987	alias(&paraml);
1988
1989#ifdef BSDJOBS
1990	/*
1991	 * If we are interactive, try to continue jobs that we have stopped
1992	 */
1993	if (prompt)
1994	    continue_jobs(&paraml);
1995#endif				/* BSDJOBS */
1996
1997	/*
1998	 * Check to see if the user typed "rm * .o" or something
1999	 */
2000	if (prompt)
2001	    rmstar(&paraml);
2002	/*
2003	 * Parse the words of the input into a parse tree.
2004	 */
2005	t = syntax(paraml.next, &paraml, 0);
2006	cleanup_push(t, syntax_cleanup);
2007	if (seterr)
2008	    stderror(ERR_OLD);
2009
2010	postcmd();
2011	/*
2012	 * Execute the parse tree From: Michael Schroeder
2013	 * <mlschroe@immd4.informatik.uni-erlangen.de> was execute(t, tpgrp);
2014	 */
2015	execute(t, (tpgrp > 0 ? tpgrp : -1), NULL, NULL, TRUE);
2016
2017	/*
2018	 * Made it!
2019	 */
2020#ifdef SIG_WINDOW
2021	if (windowchg || (catch && intty && !whyles && !tellwhat)) {
2022	    (void) check_window_size(0);	/* for window systems */
2023	}
2024#endif /* SIG_WINDOW */
2025	setcopy(STR_, InputBuf, VAR_READWRITE | VAR_NOGLOB);
2026    cmd_done:
2027	cleanup_until(&paraml);
2028    }
2029    exitset--;
2030    cleanup_pop_mark(omark);
2031    resexit(osetexit);
2032}
2033
2034/*ARGSUSED*/
2035void
2036dosource(Char **t, struct command *c)
2037{
2038    Char *f;
2039    int    hflg = 0;
2040    char *file;
2041
2042    USE(c);
2043    t++;
2044    if (*t && eq(*t, STRmh)) {
2045	if (*++t == NULL)
2046	    stderror(ERR_NAME | ERR_HFLAG);
2047	hflg++;
2048    }
2049    else if (*t && eq(*t, STRmm)) {
2050    	if (*++t == NULL)
2051	    stderror(ERR_NAME | ERR_MFLAG);
2052	hflg = 2;
2053    }
2054
2055    f = globone(*t++, G_ERROR);
2056    file = strsave(short2str(f));
2057    cleanup_push(file, xfree);
2058    xfree(f);
2059    t = glob_all_or_error(t);
2060    if ((!srcfile(file, 0, hflg, t)) && (!hflg) && (!bequiet))
2061	stderror(ERR_SYSTEM, file, strerror(errno));
2062    cleanup_until(file);
2063}
2064
2065/*
2066 * Check for mail.
2067 * If we are a login shell, then we don't want to tell
2068 * about any mail file unless its been modified
2069 * after the time we started.
2070 * This prevents us from telling the user things he already
2071 * knows, since the login program insists on saying
2072 * "You have mail."
2073 */
2074
2075/*
2076 * The AMS version.
2077 * This version checks if the file is a directory, and if so,
2078 * tells you the number of files in it, otherwise do the old thang.
2079 * The magic "+1" in the time calculation is to compensate for
2080 * an AFS bug where directory mtimes are set to 1 second in
2081 * the future.
2082 */
2083
2084static void
2085mailchk(void)
2086{
2087    struct varent *v;
2088    Char **vp;
2089    time_t  t;
2090    int     intvl, cnt;
2091    struct stat stb;
2092    int    new;
2093
2094    v = adrof(STRmail);
2095    if (v == NULL || v->vec == NULL)
2096	return;
2097    (void) time(&t);
2098    vp = v->vec;
2099    cnt = blklen(vp);
2100    intvl = (cnt && number(*vp)) ? (--cnt, getn(*vp++)) : MAILINTVL;
2101    if (intvl < 1)
2102	intvl = 1;
2103    if (chktim + intvl > t)
2104	return;
2105    for (; *vp; vp++) {
2106	char *filename = short2str(*vp);
2107	char *mboxdir = filename;
2108
2109	if (stat(filename, &stb) < 0)
2110	    continue;
2111#if defined(BSDTIMES) || defined(_SEQUENT_)
2112	new = stb.st_mtime > time0.tv_sec;
2113#else
2114	new = stb.st_mtime > seconds0;
2115#endif
2116	if (S_ISDIR(stb.st_mode)) {
2117	    DIR *mailbox;
2118	    int mailcount = 0;
2119	    char *tempfilename;
2120	    struct stat stc;
2121
2122	    tempfilename = xasprintf("%s/new", filename);
2123
2124	    if (stat(tempfilename, &stc) != -1 && S_ISDIR(stc.st_mode)) {
2125		/*
2126		 * "filename/new" exists and is a directory; you are
2127		 * using Qmail.
2128		 */
2129		stb = stc;
2130#if defined(BSDTIMES) || defined(_SEQUENT_)
2131		new = stb.st_mtime > time0.tv_sec;
2132#else
2133		new = stb.st_mtime > seconds0;
2134#endif
2135		mboxdir = tempfilename;
2136	    }
2137
2138	    if (stb.st_mtime <= chktim + 1 || (loginsh && !new)) {
2139		xfree(tempfilename);
2140		continue;
2141	    }
2142
2143	    mailbox = opendir(mboxdir);
2144	    xfree(tempfilename);
2145	    if (mailbox == NULL)
2146		continue;
2147
2148	    /* skip . and .. */
2149	    if (!readdir(mailbox) || !readdir(mailbox))
2150		continue;
2151
2152	    while (readdir(mailbox))
2153		mailcount++;
2154
2155	    if (mailcount == 0)
2156		continue;
2157
2158	    if (cnt == 1)
2159		xprintf(CGETS(11, 3, "You have %d mail messages.\n"),
2160			mailcount);
2161	    else
2162		xprintf(CGETS(11, 4, "You have %d mail messages in %s.\n"),
2163			mailcount, filename);
2164	}
2165	else {
2166	    char *type;
2167
2168	    if (stb.st_size == 0 || stb.st_atime > stb.st_mtime ||
2169		(stb.st_atime <= chktim && stb.st_mtime <= chktim) ||
2170		(loginsh && !new))
2171		continue;
2172	    type = strsave(new ? CGETS(11, 6, "new ") : "");
2173	    cleanup_push(type, xfree);
2174	    if (cnt == 1)
2175		xprintf(CGETS(11, 5, "You have %smail.\n"), type);
2176	    else
2177	        xprintf(CGETS(11, 7, "You have %smail in %s.\n"), type, filename);
2178	    cleanup_until(type);
2179	}
2180    }
2181    chktim = t;
2182}
2183
2184/*
2185 * Extract a home directory from the password file
2186 * The argument points to a buffer where the name of the
2187 * user whose home directory is sought is currently.
2188 * We return home directory of the user, or NULL.
2189 */
2190Char *
2191gethdir(const Char *home)
2192{
2193    Char   *h;
2194
2195    /*
2196     * Is it us?
2197     */
2198    if (*home == '\0') {
2199	if ((h = varval(STRhome)) != STRNULL)
2200	    return Strsave(h);
2201	else
2202	    return NULL;
2203    }
2204
2205    /*
2206     * Look in the cache
2207     */
2208    if ((h = gettilde(home)) == NULL)
2209	return NULL;
2210    else
2211	return Strsave(h);
2212}
2213
2214/*
2215 * Move the initial descriptors to their eventual
2216 * resting places, closing all other units.
2217 */
2218void
2219initdesc(void)
2220{
2221#ifdef NLS_BUGS
2222#ifdef NLS_CATALOGS
2223    nlsclose();
2224#endif /* NLS_CATALOGS */
2225#endif /* NLS_BUGS */
2226
2227
2228    didfds = 0;			/* 0, 1, 2 aren't set up */
2229    (void) close_on_exec(SHIN = dcopy(0, FSHIN), 1);
2230    (void) close_on_exec(SHOUT = dcopy(1, FSHOUT), 1);
2231    (void) close_on_exec(SHDIAG = dcopy(2, FSHDIAG), 1);
2232    (void) close_on_exec(OLDSTD = dcopy(SHIN, FOLDSTD), 1);
2233#ifndef CLOSE_ON_EXEC
2234    didcch = 0;			/* Havent closed for child */
2235#endif /* CLOSE_ON_EXEC */
2236    isdiagatty = isatty(SHDIAG);
2237    isoutatty = isatty(SHOUT);
2238#ifdef NLS_BUGS
2239#ifdef NLS_CATALOGS
2240    nlsinit();
2241#endif /* NLS_CATALOGS */
2242#endif /* NLS_BUGS */
2243}
2244
2245
2246void
2247#ifdef PROF
2248done(int i)
2249#else
2250xexit(int i)
2251#endif
2252{
2253#ifdef TESLA
2254    if (loginsh && do_logout) {
2255	/* this is to send hangup signal to the develcon */
2256	/* we toggle DTR. clear dtr - sleep 1 - set dtr */
2257	/* ioctl will return ENOTTY for pty's but we ignore it 	 */
2258	/* exitstat will run after disconnect */
2259	/* we sleep for 2 seconds to let things happen in */
2260	/* .logout and rechist() */
2261#ifdef TIOCCDTR
2262	(void) sleep(2);
2263	(void) ioctl(FSHTTY, TIOCCDTR, NULL);
2264	(void) sleep(1);
2265	(void) ioctl(FSHTTY, TIOCSDTR, NULL);
2266#endif /* TIOCCDTR */
2267    }
2268#endif /* TESLA */
2269
2270    {
2271	struct process *pp, *np;
2272
2273	/* Kill all processes marked for hup'ing */
2274	for (pp = proclist.p_next; pp; pp = pp->p_next) {
2275	    np = pp;
2276	    do
2277		if ((np->p_flags & PHUP) && np->p_jobid != shpgrp) {
2278		    if (killpg(np->p_jobid, SIGHUP) != -1) {
2279			/* In case the job was suspended... */
2280#ifdef SIGCONT
2281			(void) killpg(np->p_jobid, SIGCONT);
2282#endif
2283			break;
2284		    }
2285		}
2286	    while ((np = np->p_friends) != pp);
2287	}
2288    }
2289    untty();
2290#ifdef NLS_CATALOGS
2291    /*
2292     * We need to call catclose, because SVR4 leaves symlinks behind otherwise
2293     * in the catalog directories. We cannot close on a vforked() child,
2294     * because messages will stop working on the parent too.
2295     */
2296    if (child == 0)
2297	nlsclose();
2298#endif /* NLS_CATALOGS */
2299#ifdef WINNT_NATIVE
2300    nt_cleanup();
2301#endif /* WINNT_NATIVE */
2302    _exit(i);
2303}
2304
2305#ifndef _PATH_DEFPATH
2306static Char **
2307defaultpath(void)
2308{
2309    char   *ptr;
2310    Char  **blk, **blkp;
2311    struct stat stb;
2312
2313    blkp = blk = xmalloc(sizeof(Char *) * 10);
2314
2315#ifndef NODOT
2316# ifndef DOTLAST
2317    *blkp++ = Strsave(STRdot);
2318# endif
2319#endif
2320
2321#define DIRAPPEND(a)  \
2322	if (stat(ptr = a, &stb) == 0 && S_ISDIR(stb.st_mode)) \
2323		*blkp++ = SAVE(ptr)
2324
2325#ifdef _PATH_LOCAL
2326    DIRAPPEND(_PATH_LOCAL);
2327#endif
2328
2329#ifdef _PATH_USRUCB
2330    DIRAPPEND(_PATH_USRUCB);
2331#endif
2332
2333#ifdef _PATH_USRBSD
2334    DIRAPPEND(_PATH_USRBSD);
2335#endif
2336
2337#ifdef _PATH_BIN
2338    DIRAPPEND(_PATH_BIN);
2339#endif
2340
2341#ifdef _PATH_USRBIN
2342    DIRAPPEND(_PATH_USRBIN);
2343#endif
2344
2345#undef DIRAPPEND
2346
2347#ifndef NODOT
2348# ifdef DOTLAST
2349    *blkp++ = Strsave(STRdot);
2350# endif
2351#endif
2352    *blkp = NULL;
2353    return (blk);
2354}
2355#endif
2356
2357static void
2358record(void)
2359{
2360    if (!fast) {
2361	recdirs(NULL, adrof(STRsavedirs) != NULL);
2362	rechist(NULL, adrof(STRsavehist) != NULL);
2363    }
2364}
2365