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