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