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