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