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