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