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