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