tc.func.c revision 316958
1/* $Header: /p/tcsh/cvsroot/tcsh/tc.func.c,v 3.158 2016/05/13 15:08:12 christos Exp $ */
2/*
3 * tc.func.c: New tcsh builtins.
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#include "sh.h"
34
35RCSID("$tcsh: tc.func.c,v 3.158 2016/05/13 15:08:12 christos Exp $")
36
37#include "ed.h"
38#include "ed.defns.h"		/* for the function names */
39#include "tw.h"
40#include "tc.h"
41#ifdef WINNT_NATIVE
42#include "nt.const.h"
43#else /* WINNT_NATIVE */
44#include <sys/wait.h>
45#endif /* WINNT_NATIVE */
46
47#ifdef AFS
48#include <afs/stds.h>
49#include <afs/kautils.h>
50long ka_UserAuthenticateGeneral();
51#endif /* AFS */
52
53#ifdef TESLA
54extern int do_logout;
55#endif /* TESLA */
56extern time_t t_period;
57extern int just_signaled;
58static int precmd_active = 0;
59static int jobcmd_active = 0; /* GrP */
60static int postcmd_active = 0;
61static int periodic_active = 0;
62static int cwdcmd_active = 0;	/* PWP: for cwd_cmd */
63static int beepcmd_active = 0;
64static void (*alm_fun)(void) = NULL;
65
66static	void	 auto_logout	(void);
67static	char	*xgetpass	(const char *);
68static	void	 auto_lock	(void);
69#ifdef BSDJOBS
70static	void	 insert		(struct wordent *, int);
71static	void	 insert_we	(struct wordent *, struct wordent *);
72static	int	 inlist		(Char *, Char *);
73#endif /* BSDJOBS */
74static	int	 tildecompare	(const void *, const void *);
75static  Char    *gethomedir	(const Char *);
76#ifdef REMOTEHOST
77static	void	 palarm		(int);
78static	void	 getremotehost	(int);
79#endif /* REMOTEHOST */
80
81/*
82 * Tops-C shell
83 */
84
85/*
86 * expand_lex: Take the given lex and return an expanded version of it.
87 * First guy in lex list is ignored; last guy is ^J which we ignore.
88 * Only take lex'es from position 'from' to position 'to' inclusive
89 *
90 * Note: csh sometimes sets bit 8 in characters which causes all kinds
91 * of problems if we don't mask it here. Note: excl's in lexes have been
92 * un-back-slashed and must be re-back-slashed
93 *
94 */
95/* PWP: this is a combination of the old sprlex() and the expand_lex from
96   the magic-space stuff */
97
98Char   *
99expand_lex(const struct wordent *sp0, int from, int to)
100{
101    struct Strbuf buf = Strbuf_INIT;
102    const struct wordent *sp;
103    Char *s;
104    Char prev_c;
105    int i;
106
107    prev_c = '\0';
108
109    if (!sp0 || (sp = sp0->next) == sp0 || sp == (sp0 = sp0->prev))
110	return Strbuf_finish(&buf); /* null lex */
111
112    for (i = 0; ; i++) {
113	if ((i >= from) && (i <= to)) {	/* if in range */
114	    for (s = sp->word; *s; s++) {
115		/*
116		 * bugfix by Michael Bloom: anything but the current history
117		 * character {(PWP) and backslash} seem to be dealt with
118		 * elsewhere.
119		 */
120		if ((*s & QUOTE)
121		    && (((*s & TRIM) == HIST && HIST != '\0') ||
122			(((*s & TRIM) == '\'') && (prev_c != '\\')) ||
123			(((*s & TRIM) == '\"') && (prev_c != '\\')))) {
124		    Strbuf_append1(&buf, '\\');
125		}
126#if INVALID_BYTE != 0
127		if ((*s & INVALID_BYTE) != INVALID_BYTE) /* *s < INVALID_BYTE */
128		    Strbuf_append1(&buf, *s & TRIM);
129		else
130		    Strbuf_append1(&buf, *s);
131#else
132		Strbuf_append1(&buf, *s & TRIM);
133#endif
134		prev_c = *s;
135	    }
136	    Strbuf_append1(&buf, ' ');
137	}
138	sp = sp->next;
139	if (sp == sp0)
140	    break;
141    }
142    if (buf.len != 0)
143	buf.len--;		/* get rid of trailing space */
144
145    return Strbuf_finish(&buf);
146}
147
148Char   *
149sprlex(const struct wordent *sp0)
150{
151    return expand_lex(sp0, 0, INT_MAX);
152}
153
154
155Char *
156Itoa(int n, size_t min_digits, Char attributes)
157{
158    /*
159     * The array size here is derived from
160     *	log8(UINT_MAX)
161     * which is guaranteed to be enough for a decimal
162     * representation.  We add 1 because integer divide
163     * rounds down.
164     */
165#ifndef CHAR_BIT
166# define CHAR_BIT 8
167#endif
168    Char buf[CHAR_BIT * sizeof(int) / 3 + 1], *res, *p, *s;
169    unsigned int un;	/* handle most negative # too */
170    int pad = (min_digits != 0);
171
172    if (sizeof(buf) - 1 < min_digits)
173	min_digits = sizeof(buf) - 1;
174
175    un = n;
176    if (n < 0)
177	un = -n;
178
179    p = buf;
180    do {
181	*p++ = un % 10 + '0';
182	un /= 10;
183    } while ((pad && (ssize_t)--min_digits > 0) || un != 0);
184
185    res = xmalloc((p - buf + 2) * sizeof(*res));
186    s = res;
187    if (n < 0)
188	*s++ = '-';
189    while (p > buf)
190	*s++ = *--p | attributes;
191
192    *s = '\0';
193    return res;
194}
195
196
197/*ARGSUSED*/
198void
199dolist(Char **v, struct command *c)
200{
201    Char **globbed;
202    int     i, k, ret = 0;
203    struct stat st;
204
205    USE(c);
206    if (*++v == NULL) {
207	struct Strbuf word = Strbuf_INIT;
208
209	Strbuf_terminate(&word);
210	cleanup_push(&word, Strbuf_cleanup);
211	(void) t_search(&word, LIST, TW_ZERO, 0, STRNULL, 0);
212	cleanup_until(&word);
213	return;
214    }
215    v = glob_all_or_error(v);
216    globbed = v;
217    cleanup_push(globbed, blk_cleanup);
218    for (k = 0; v[k] != NULL && v[k][0] != '-'; k++)
219	continue;
220    if (v[k]) {
221	/*
222	 * We cannot process a flag therefore we let ls do it right.
223	 */
224	Char *lspath;
225	struct command *t;
226	struct wordent cmd, *nextword, *lastword;
227	Char   *cp;
228	struct varent *vp;
229
230	if (setintr) {
231	    pintr_disabled++;
232	    cleanup_push(&pintr_disabled, disabled_cleanup);
233	}
234	if (seterr) {
235	    xfree(seterr);
236	    seterr = NULL;
237	}
238
239	lspath = STRls;
240	STRmCF[1] = 'C';
241	STRmCF[3] = '\0';
242	/* Look at listflags, to add -A to the flags, to get a path
243	   of ls if necessary */
244	if ((vp = adrof(STRlistflags)) != NULL && vp->vec != NULL &&
245	    vp->vec[0] != STRNULL) {
246	    if (vp->vec[1] != NULL && vp->vec[1][0] != '\0')
247		lspath = vp->vec[1];
248	    for (cp = vp->vec[0]; *cp; cp++)
249		switch (*cp) {
250		case 'x':
251		    STRmCF[1] = 'x';
252		    break;
253		case 'a':
254		    STRmCF[3] = 'a';
255		    break;
256		case 'A':
257		    STRmCF[3] = 'A';
258		    break;
259		default:
260		    break;
261		}
262	}
263
264	cmd.word = STRNULL;
265	lastword = &cmd;
266	nextword = xcalloc(1, sizeof cmd);
267	nextword->word = Strsave(lspath);
268	lastword->next = nextword;
269	nextword->prev = lastword;
270	lastword = nextword;
271	nextword = xcalloc(1, sizeof cmd);
272	nextword->word = Strsave(STRmCF);
273	lastword->next = nextword;
274	nextword->prev = lastword;
275#if defined(KANJI) && defined(SHORT_STRINGS) && defined(DSPMBYTE)
276	if (dspmbyte_ls) {
277	    lastword = nextword;
278	    nextword = xcalloc(1, sizeof cmd);
279	    nextword->word = Strsave(STRmmliteral);
280	    lastword->next = nextword;
281	    nextword->prev = lastword;
282	}
283#endif
284#ifdef COLOR_LS_F
285	if (color_context_ls) {
286	    lastword = nextword;
287	    nextword = xcalloc(1, sizeof cmd);
288	    nextword->word = Strsave(STRmmcolormauto);
289	    lastword->next = nextword;
290	    nextword->prev = lastword;
291	}
292#endif /* COLOR_LS_F */
293	lastword = nextword;
294	for (cp = *v; cp; cp = *++v) {
295	    nextword = xcalloc(1, sizeof cmd);
296	    nextword->word = quote(Strsave(cp));
297	    lastword->next = nextword;
298	    nextword->prev = lastword;
299	    lastword = nextword;
300	}
301	lastword->next = &cmd;
302	cmd.prev = lastword;
303	cleanup_push(&cmd, lex_cleanup);
304
305	/* build a syntax tree for the command. */
306	t = syntax(cmd.next, &cmd, 0);
307	cleanup_push(t, syntax_cleanup);
308	if (seterr)
309	    stderror(ERR_OLD);
310	/* expand aliases like process() does */
311	/* alias(&cmd); */
312	/* execute the parse tree. */
313	execute(t, tpgrp > 0 ? tpgrp : -1, NULL, NULL, FALSE);
314	/* done. free the lex list and parse tree. */
315	cleanup_until(&cmd);
316	if (setintr)
317	    cleanup_until(&pintr_disabled);
318    }
319    else {
320	Char   *dp, *tmp;
321	struct Strbuf buf = Strbuf_INIT;
322
323	cleanup_push(&buf, Strbuf_cleanup);
324	for (k = 0, i = 0; v[k] != NULL; k++) {
325	    tmp = dnormalize(v[k], symlinks == SYM_IGNORE);
326	    cleanup_push(tmp, xfree);
327	    dp = Strend(tmp) - 1;
328	    if (*dp == '/' && dp != tmp)
329#ifdef apollo
330		if (dp != &tmp[1])
331#endif /* apollo */
332		*dp = '\0';
333	    if (stat(short2str(tmp), &st) == -1) {
334		int err;
335
336		err = errno;
337		if (k != i) {
338		    if (i != 0)
339			xputchar('\n');
340		    print_by_column(STRNULL, &v[i], k - i, FALSE);
341		}
342		haderr = 1;
343		xprintf("%S: %s.\n", tmp, strerror(err));
344		haderr = 0;
345		i = k + 1;
346		ret = 1;
347	    }
348	    else if (S_ISDIR(st.st_mode)) {
349		Char   *cp;
350
351		if (k != i) {
352		    if (i != 0)
353			xputchar('\n');
354		    print_by_column(STRNULL, &v[i], k - i, FALSE);
355		}
356		if (k != 0 && v[1] != NULL)
357		    xputchar('\n');
358		xprintf("%S:\n", tmp);
359		buf.len = 0;
360		for (cp = tmp; *cp; cp++)
361		    Strbuf_append1(&buf, (*cp | QUOTE));
362		Strbuf_terminate(&buf);
363		dp = &buf.s[buf.len - 1];
364		if (
365#ifdef WINNT_NATIVE
366		    (*dp != (Char) (':' | QUOTE)) &&
367#endif /* WINNT_NATIVE */
368		    (*dp != (Char) ('/' | QUOTE))) {
369		    Strbuf_append1(&buf, '/');
370		    Strbuf_terminate(&buf);
371		} else
372		    *dp &= TRIM;
373		(void) t_search(&buf, LIST, TW_ZERO, 0, STRNULL, 0);
374		i = k + 1;
375	    }
376	    cleanup_until(tmp);
377	}
378	cleanup_until(&buf);
379	if (k != i) {
380	    if (i != 0)
381		xputchar('\n');
382	    print_by_column(STRNULL, &v[i], k - i, FALSE);
383	}
384	if (ret)
385	    stderror(ERR_SILENT);
386    }
387
388    cleanup_until(globbed);
389}
390
391extern int GotTermCaps;
392
393/*ARGSUSED*/
394void
395dotelltc(Char **v, struct command *c)
396{
397    USE(v);
398    USE(c);
399    if (!GotTermCaps)
400	GetTermCaps();
401    TellTC();
402}
403
404/*ARGSUSED*/
405void
406doechotc(Char **v, struct command *c)
407{
408    USE(c);
409    if (!GotTermCaps)
410	GetTermCaps();
411    EchoTC(++v);
412}
413
414/*ARGSUSED*/
415void
416dosettc(Char **v, struct command *c)
417{
418    char    *tv[2];
419
420    USE(c);
421    if (!GotTermCaps)
422	GetTermCaps();
423
424    tv[0] = strsave(short2str(v[1]));
425    cleanup_push(tv[0], xfree);
426    tv[1] = strsave(short2str(v[2]));
427    cleanup_push(tv[1], xfree);
428    SetTC(tv[0], tv[1]);
429    cleanup_until(tv[0]);
430}
431
432/* The dowhich() is by:
433 *  Andreas Luik <luik@isaak.isa.de>
434 *  I S A  GmbH - Informationssysteme fuer computerintegrierte Automatisierung
435 *  Azenberstr. 35
436 *  D-7000 Stuttgart 1
437 *  West-Germany
438 * Thanks!!
439 */
440int
441cmd_expand(Char *cmd, Char **str)
442{
443    struct wordent lexp[3];
444    struct varent *vp;
445    int rv = TRUE;
446
447    lexp[0].next = &lexp[1];
448    lexp[1].next = &lexp[2];
449    lexp[2].next = &lexp[0];
450
451    lexp[0].prev = &lexp[2];
452    lexp[1].prev = &lexp[0];
453    lexp[2].prev = &lexp[1];
454
455    lexp[0].word = STRNULL;
456    lexp[2].word = STRret;
457
458    if ((vp = adrof1(cmd, &aliases)) != NULL && vp->vec != NULL) {
459	if (str == NULL) {
460	    xprintf(CGETS(22, 1, "%S: \t aliased to "), cmd);
461	    blkpr(vp->vec);
462	    xputchar('\n');
463	}
464	else
465	    *str = blkexpand(vp->vec);
466    }
467    else {
468	lexp[1].word = cmd;
469	rv = tellmewhat(lexp, str);
470    }
471    return rv;
472}
473
474
475/*ARGSUSED*/
476void
477dowhich(Char **v, struct command *c)
478{
479    int rv = TRUE;
480    USE(c);
481
482    /*
483     * We don't want to glob dowhich args because we lose quoteing
484     * E.g. which \ls if ls is aliased will not work correctly if
485     * we glob here.
486     */
487
488    while (*++v)
489	rv &= cmd_expand(*v, NULL);
490
491    if (!rv)
492	setcopy(STRstatus, STR1, VAR_READWRITE);
493}
494
495static int
496findvv(Char **vv, const char *cp)
497{
498    for (; vv && *vv; vv++) {
499	size_t i;
500	for (i = 0; (*vv)[i] && (*vv)[i] == cp[i]; i++)
501	    continue;
502	if ((*vv)[i] == '\0' && cp[i] == '\0')
503	    return 1;
504    }
505    return 0;
506}
507
508/* PWP: a hack to start up your stopped editor on a single keystroke */
509/* jbs - fixed hack so it worked :-) 3/28/89 */
510
511struct process *
512find_stop_ed(void)
513{
514    struct process *pp, *retp;
515    const char *ep = NULL, *vp = NULL;
516    char *cp, *p;
517    size_t epl = 0, vpl = 0;
518    int pstatus;
519    struct varent *varp;
520    Char **vv;
521
522    if (pcurrent == NULL)	/* see if we have any jobs */
523	return NULL;		/* nope */
524
525    if ((varp = adrof(STReditors)) != NULL)
526	vv = varp->vec;
527    else
528	vv = NULL;
529
530    if (! vv) {
531	if ((ep = getenv("EDITOR")) != NULL) {	/* if we have a value */
532	    if ((p = strrchr(ep, '/')) != NULL) 	/* if it has a path */
533		ep = p + 1;		/* then we want only the last part */
534	}
535	else
536	    ep = "ed";
537
538	if ((vp = getenv("VISUAL")) != NULL) {	/* if we have a value */
539	    if ((p = strrchr(vp, '/')) != NULL) 	/* and it has a path */
540		vp = p + 1;		/* then we want only the last part */
541	}
542	else
543	    vp = "vi";
544
545	for (vpl = 0; vp[vpl] && !isspace((unsigned char)vp[vpl]); vpl++)
546	    continue;
547	for (epl = 0; ep[epl] && !isspace((unsigned char)ep[epl]); epl++)
548	    continue;
549    }
550
551    retp = NULL;
552    for (pp = proclist.p_next; pp; pp = pp->p_next)
553	if (pp->p_procid == pp->p_jobid) {
554
555	    /*
556	     * Only foreground an edit session if it is suspended.  Some GUI
557	     * editors have may be happily running in a separate window, no
558	     * point in foregrounding these if they're already running - webb
559	     */
560	    pstatus = (int) (pp->p_flags & PALLSTATES);
561	    if (pstatus != PINTERRUPTED && pstatus != PSTOPPED &&
562		pstatus != PSIGNALED)
563		continue;
564
565	    p = short2str(pp->p_command);
566	    /* get the first word */
567	    for (cp = p; *cp && !isspace((unsigned char) *cp); cp++)
568		continue;
569	    *cp = '\0';
570
571	    if ((cp = strrchr(p, '/')) != NULL)	/* and it has a path */
572		cp = cp + 1;		/* then we want only the last part */
573	    else
574		cp = p;			/* else we get all of it */
575
576	    /*
577	     * If we find the current name in the $editors array (if set)
578	     * or as $EDITOR or $VISUAL (if $editors not set), fg it.
579	     */
580	    if ((vv && findvv(vv, cp)) ||
581	        (epl && strncmp(ep, cp, epl) == 0 && cp[epl] == '\0') ||
582		(vpl && strncmp(vp, cp, vpl) == 0 && cp[vpl] == '\0')) {
583		/*
584		 * If there is a choice, then choose the current process if
585		 * available, or the previous process otherwise, or else
586		 * anything will do - Robert Webb (robertw@mulga.cs.mu.oz.au).
587		 */
588		if (pp == pcurrent)
589		    return pp;
590		else if (retp == NULL || pp == pprevious)
591		    retp = pp;
592	    }
593	}
594
595    return retp;		/* Will be NULL if we didn't find a job */
596}
597
598void
599fg_proc_entry(struct process *pp)
600{
601    jmp_buf_t osetexit;
602    int    ohaderr;
603    Char    oGettingInput;
604    size_t omark;
605
606    getexit(osetexit);
607
608    pintr_disabled++;
609    oGettingInput = GettingInput;
610    GettingInput = 0;
611
612    ohaderr = haderr;		/* we need to ignore setting of haderr due to
613				 * process getting stopped by a signal */
614    omark = cleanup_push_mark();
615    if (setexit() == 0) {	/* come back here after pjwait */
616	pendjob();
617	(void) alarm(0);	/* No autologout */
618	alrmcatch_disabled = 1;
619	if (!pstart(pp, 1)) {
620	    pp->p_procid = 0;
621	    stderror(ERR_BADJOB, pp->p_command, strerror(errno));
622	}
623	pjwait(pp);
624    }
625    setalarm(1);		/* Autologout back on */
626    cleanup_pop_mark(omark);
627    resexit(osetexit);
628    haderr = ohaderr;
629    GettingInput = oGettingInput;
630
631    disabled_cleanup(&pintr_disabled);
632}
633
634static char *
635xgetpass(const char *prm)
636{
637    static struct strbuf pass; /* = strbuf_INIT; */
638    int fd;
639    sigset_t oset, set;
640    struct sigaction sa, osa;
641
642    sa.sa_handler = SIG_IGN;
643    sigemptyset(&sa.sa_mask);
644    sa.sa_flags = 0;
645    (void)sigaction(SIGINT, &sa, &osa);
646
647    sigemptyset(&set);
648    sigaddset(&set, SIGINT);
649    (void)sigprocmask(SIG_UNBLOCK, &set, &oset);
650
651    cleanup_push(&osa, sigint_cleanup);
652    cleanup_push(&oset, sigprocmask_cleanup);
653    (void) Rawmode();	/* Make sure, cause we want echo off */
654    fd = xopen("/dev/tty", O_RDWR|O_LARGEFILE);
655    if (fd == -1)
656	fd = SHIN;
657    else
658	cleanup_push(&fd, open_cleanup);
659
660    xprintf("%s", prm); flush();
661    pass.len = 0;
662    for (;;)  {
663	char c;
664
665	if (xread(fd, &c, 1) < 1 || c == '\n')
666	    break;
667	strbuf_append1(&pass, c);
668    }
669    strbuf_terminate(&pass);
670
671    cleanup_until(&osa);
672
673    return pass.s;
674}
675
676#ifndef NO_CRYPT
677#if !HAVE_DECL_CRYPT
678    extern char *crypt ();
679#endif
680#ifdef HAVE_CRYPT_H
681#include <crypt.h>
682#endif
683#endif
684
685/*
686 * Ask the user for his login password to continue working
687 * On systems that have a shadow password, this will only
688 * work for root, but what can we do?
689 *
690 * If we fail to get the password, then we log the user out
691 * immediately
692 */
693/*ARGSUSED*/
694static void
695auto_lock(void)
696{
697#ifndef NO_CRYPT
698
699    int i;
700    char *srpp = NULL;
701    struct passwd *pw;
702
703#undef XCRYPT
704
705#if defined(HAVE_AUTH_H) && defined(HAVE_GETAUTHUID)
706
707    struct authorization *apw;
708    extern char *crypt16 (const char *, const char *);
709
710# define XCRYPT(pw, a, b) crypt16(a, b)
711
712    if ((pw = xgetpwuid(euid)) != NULL &&	/* effective user passwd  */
713        (apw = getauthuid(euid)) != NULL) 	/* enhanced ultrix passwd */
714	srpp = apw->a_password;
715
716#elif defined(HAVE_SHADOW_H)
717
718    struct spwd *spw;
719
720# define XCRYPT(pw, a, b) crypt(a, b)
721
722    if ((pw = xgetpwuid(euid)) != NULL)	{	/* effective user passwd  */
723	errno = 0;
724	while ((spw = getspnam(pw->pw_name)) == NULL && errno == EINTR) {
725	    handle_pending_signals();
726	    errno = 0;
727	}
728	if (spw != NULL)			 /* shadowed passwd	  */
729	    srpp = spw->sp_pwdp;
730    }
731
732#else
733
734
735#ifdef __CYGWIN__
736# define XCRYPT(pw, a, b) cygwin_xcrypt(pw, a, b)
737#else
738# define XCRYPT(pw, a, b) crypt(a, b)
739#endif
740
741#if !defined(__MVS__)
742    if ((pw = xgetpwuid(euid)) != NULL)	/* effective user passwd  */
743	srpp = pw->pw_passwd;
744#endif /* !MVS */
745
746#endif
747
748    if (srpp == NULL) {
749	auto_logout();
750	/*NOTREACHED*/
751	return;
752    }
753
754    setalarm(0);		/* Not for locking any more */
755    xputchar('\n');
756    for (i = 0; i < 5; i++) {
757	const char *crpp;
758	char *pp;
759#ifdef AFS
760	char *afsname;
761	Char *safs;
762
763	if ((safs = varval(STRafsuser)) != STRNULL)
764	    afsname = short2str(safs);
765	else
766	    if ((afsname = getenv("AFSUSER")) == NULL)
767	        afsname = pw->pw_name;
768#endif
769	pp = xgetpass("Password:");
770
771	crpp = XCRYPT(pw, pp, srpp);
772	if ((crpp && strcmp(crpp, srpp) == 0)
773#ifdef AFS
774	    || (ka_UserAuthenticateGeneral(KA_USERAUTH_VERSION,
775					   afsname,     /* name */
776					   NULL,        /* instance */
777					   NULL,        /* realm */
778					   pp,          /* password */
779					   0,           /* lifetime */
780					   0, 0,         /* spare */
781					   NULL)        /* reason */
782	    == 0)
783#endif /* AFS */
784	    ) {
785	    (void) memset(pp, 0, strlen(pp));
786	    if (GettingInput && !just_signaled) {
787		(void) Rawmode();
788		ClearLines();
789		ClearDisp();
790		Refresh();
791	    }
792	    just_signaled = 0;
793	    return;
794	}
795	xprintf(CGETS(22, 2, "\nIncorrect passwd for %s\n"), pw->pw_name);
796    }
797#endif /* NO_CRYPT */
798    auto_logout();
799}
800
801
802static void
803auto_logout(void)
804{
805    xprintf("auto-logout\n");
806    /* Don't leave the tty in raw mode */
807    if (editing)
808	(void) Cookedmode();
809    xclose(SHIN);
810    setcopy(STRlogout, STRautomatic, VAR_READWRITE);
811    child = 1;
812#ifdef TESLA
813    do_logout = 1;
814#endif /* TESLA */
815    GettingInput = FALSE; /* make flush() work to write hist files. Huber*/
816    goodbye(NULL, NULL);
817}
818
819void
820alrmcatch(void)
821{
822    (*alm_fun)();
823    setalarm(1);
824}
825
826/*
827 * Karl Kleinpaste, 21oct1983.
828 * Added precmd(), which checks for the alias
829 * precmd in aliases.  If it's there, the alias
830 * is executed as a command.  This is done
831 * after mailchk() and just before print-
832 * ing the prompt.  Useful for things like printing
833 * one's current directory just before each command.
834 */
835void
836precmd(void)
837{
838    pintr_disabled++;
839    cleanup_push(&pintr_disabled, disabled_cleanup);
840    if (precmd_active) {	/* an error must have been caught */
841	aliasrun(2, STRunalias, STRprecmd);
842	xprintf("%s", CGETS(22, 3, "Faulty alias 'precmd' removed.\n"));
843	goto leave;
844    }
845    precmd_active = 1;
846    if (!whyles && adrof1(STRprecmd, &aliases))
847	aliasrun(1, STRprecmd, NULL);
848leave:
849    precmd_active = 0;
850    cleanup_until(&pintr_disabled);
851}
852
853void
854postcmd(void)
855{
856    pintr_disabled++;
857    cleanup_push(&pintr_disabled, disabled_cleanup);
858    if (postcmd_active) {	/* an error must have been caught */
859	aliasrun(2, STRunalias, STRpostcmd);
860	xprintf("%s", CGETS(22, 3, "Faulty alias 'postcmd' removed.\n"));
861	goto leave;
862    }
863    postcmd_active = 1;
864    if (!whyles && adrof1(STRpostcmd, &aliases))
865	aliasrun(1, STRpostcmd, NULL);
866leave:
867    postcmd_active = 0;
868    cleanup_until(&pintr_disabled);
869}
870
871/*
872 * Paul Placeway  11/24/87  Added cwd_cmd by hacking precmd() into
873 * submission...  Run every time $cwd is set (after it is set).  Useful
874 * for putting your machine and cwd (or anything else) in an xterm title
875 * space.
876 */
877void
878cwd_cmd(void)
879{
880    pintr_disabled++;
881    cleanup_push(&pintr_disabled, disabled_cleanup);
882    if (cwdcmd_active) {	/* an error must have been caught */
883	aliasrun(2, STRunalias, STRcwdcmd);
884	xprintf("%s", CGETS(22, 4, "Faulty alias 'cwdcmd' removed.\n"));
885	goto leave;
886    }
887    cwdcmd_active = 1;
888    if (!whyles && adrof1(STRcwdcmd, &aliases))
889	aliasrun(1, STRcwdcmd, NULL);
890leave:
891    cwdcmd_active = 0;
892    cleanup_until(&pintr_disabled);
893}
894
895/*
896 * Joachim Hoenig  07/16/91  Added beep_cmd, run every time tcsh wishes
897 * to beep the terminal bell. Useful for playing nice sounds instead.
898 */
899void
900beep_cmd(void)
901{
902    pintr_disabled++;
903    cleanup_push(&pintr_disabled, disabled_cleanup);
904    if (beepcmd_active) {	/* an error must have been caught */
905	aliasrun(2, STRunalias, STRbeepcmd);
906	xprintf("%s", CGETS(22, 5, "Faulty alias 'beepcmd' removed.\n"));
907    }
908    else {
909	beepcmd_active = 1;
910	if (!whyles && adrof1(STRbeepcmd, &aliases))
911	    aliasrun(1, STRbeepcmd, NULL);
912    }
913    beepcmd_active = 0;
914    cleanup_until(&pintr_disabled);
915}
916
917
918/*
919 * Karl Kleinpaste, 18 Jan 1984.
920 * Added period_cmd(), which executes the alias "periodic" every
921 * $tperiod minutes.  Useful for occasional checking of msgs and such.
922 */
923void
924period_cmd(void)
925{
926    Char *vp;
927    time_t  t, interval;
928
929    pintr_disabled++;
930    cleanup_push(&pintr_disabled, disabled_cleanup);
931    if (periodic_active) {	/* an error must have been caught */
932	aliasrun(2, STRunalias, STRperiodic);
933	xprintf("%s", CGETS(22, 6, "Faulty alias 'periodic' removed.\n"));
934	goto leave;
935    }
936    periodic_active = 1;
937    if (!whyles && adrof1(STRperiodic, &aliases)) {
938	vp = varval(STRtperiod);
939	if (vp == STRNULL) {
940	    aliasrun(1, STRperiodic, NULL);
941	    goto leave;
942	}
943	interval = getn(vp);
944	(void) time(&t);
945	if (t - t_period >= interval * 60) {
946	    t_period = t;
947	    aliasrun(1, STRperiodic, NULL);
948	}
949    }
950leave:
951    periodic_active = 0;
952    cleanup_until(&pintr_disabled);
953}
954
955
956/*
957 * GrP Greg Parker May 2001
958 * Added job_cmd(), which is run every time a job is started or
959 * foregrounded. The command is passed a single argument, the string
960 * used to start the job originally. With precmd, useful for setting
961 * xterm titles.
962 * Cloned from cwd_cmd().
963 */
964void
965job_cmd(Char *args)
966{
967    pintr_disabled++;
968    cleanup_push(&pintr_disabled, disabled_cleanup);
969    if (jobcmd_active) {	/* an error must have been caught */
970	aliasrun(2, STRunalias, STRjobcmd);
971	xprintf("%s", CGETS(22, 14, "Faulty alias 'jobcmd' removed.\n"));
972	goto leave;
973    }
974    jobcmd_active = 1;
975    if (!whyles && adrof1(STRjobcmd, &aliases)) {
976	struct process *pp = pcurrjob; /* put things back after the hook */
977	aliasrun(2, STRjobcmd, args);
978	pcurrjob = pp;
979    }
980leave:
981    jobcmd_active = 0;
982    cleanup_until(&pintr_disabled);
983}
984
985
986/*
987 * Karl Kleinpaste, 21oct1983.
988 * Set up a one-word alias command, for use for special things.
989 * This code is based on the mainline of process().
990 */
991void
992aliasrun(int cnt, Char *s1, Char *s2)
993{
994    struct wordent w, *new1, *new2;	/* for holding alias name */
995    struct command *t = NULL;
996    jmp_buf_t osetexit;
997    int status;
998    size_t omark;
999
1000    getexit(osetexit);
1001    if (seterr) {
1002	xfree(seterr);
1003	seterr = NULL;	/* don't repeatedly print err msg. */
1004    }
1005    w.word = STRNULL;
1006    new1 = xcalloc(1, sizeof w);
1007    new1->word = Strsave(s1);
1008    if (cnt == 1) {
1009	/* build a lex list with one word. */
1010	w.next = w.prev = new1;
1011	new1->next = new1->prev = &w;
1012    }
1013    else {
1014	/* build a lex list with two words. */
1015	new2 = xcalloc(1, sizeof w);
1016	new2->word = Strsave(s2);
1017	w.next = new2->prev = new1;
1018	new1->next = w.prev = new2;
1019	new1->prev = new2->next = &w;
1020    }
1021    cleanup_push(&w, lex_cleanup);
1022
1023    /* Save the old status */
1024    status = getn(varval(STRstatus));
1025
1026    /* expand aliases like process() does. */
1027    alias(&w);
1028    /* build a syntax tree for the command. */
1029    t = syntax(w.next, &w, 0);
1030    cleanup_push(t, syntax_cleanup);
1031    if (seterr)
1032	stderror(ERR_OLD);
1033
1034    psavejob();
1035    cleanup_push(&cnt, psavejob_cleanup); /* cnt is used only as a marker */
1036
1037    /* catch any errors here */
1038    omark = cleanup_push_mark();
1039    if (setexit() == 0)
1040	/* execute the parse tree. */
1041	/*
1042	 * From: Michael Schroeder <mlschroe@immd4.informatik.uni-erlangen.de>
1043	 * was execute(t, tpgrp);
1044	 */
1045	execute(t, tpgrp > 0 ? tpgrp : -1, NULL, NULL, TRUE);
1046    /* reset the error catcher to the old place */
1047    cleanup_pop_mark(omark);
1048    resexit(osetexit);
1049    if (haderr) {
1050	haderr = 0;
1051	/*
1052	 * Either precmd, or cwdcmd, or periodic had an error. Call it again so
1053	 * that it is removed
1054	 */
1055	if (precmd_active)
1056	    precmd();
1057	if (postcmd_active)
1058	    postcmd();
1059#ifdef notdef
1060	/*
1061	 * XXX: On the other hand, just interrupting them causes an error too.
1062	 * So if we hit ^C in the middle of cwdcmd or periodic the alias gets
1063	 * removed. We don't want that. Note that we want to remove precmd
1064	 * though, cause that could lead into an infinite loop. This should be
1065	 * fixed correctly, but then haderr should give us the whole exit
1066	 * status not just true or false.
1067	 */
1068	else if (cwdcmd_active)
1069	    cwd_cmd();
1070	else if (beepcmd_active)
1071	    beep_cmd();
1072	else if (periodic_active)
1073	    period_cmd();
1074#endif /* notdef */
1075    }
1076    cleanup_until(&w);
1077    pendjob();
1078    /* Restore status */
1079    setv(STRstatus, putn((tcsh_number_t)status), VAR_READWRITE);
1080}
1081
1082void
1083setalarm(int lck)
1084{
1085    struct varent *vp;
1086    Char   *cp;
1087    unsigned alrm_time = 0, logout_time, lock_time;
1088    time_t cl, nl, sched_dif;
1089
1090    if ((vp = adrof(STRautologout)) != NULL && vp->vec != NULL) {
1091	if ((cp = vp->vec[0]) != 0) {
1092	    if ((logout_time = (unsigned) atoi(short2str(cp)) * 60) > 0) {
1093#ifdef SOLARIS2
1094		/*
1095		 * Solaris alarm(2) uses a timer based in clock ticks
1096		 * internally so it multiplies our value with CLK_TCK...
1097		 * Of course that can overflow leading to unexpected
1098		 * results, so we clip it here. Grr. Where is that
1099		 * documented folks?
1100		 */
1101		if (logout_time >= 0x7fffffff / CLK_TCK)
1102			logout_time = 0x7fffffff / CLK_TCK;
1103#endif /* SOLARIS2 */
1104		alrm_time = logout_time;
1105		alm_fun = auto_logout;
1106	    }
1107	}
1108	if ((cp = vp->vec[1]) != 0) {
1109	    if ((lock_time = (unsigned) atoi(short2str(cp)) * 60) > 0) {
1110		if (lck) {
1111		    if (alrm_time == 0 || lock_time < alrm_time) {
1112			alrm_time = lock_time;
1113			alm_fun = auto_lock;
1114		    }
1115		}
1116		else /* lock_time always < alrm_time */
1117		    if (alrm_time)
1118			alrm_time -= lock_time;
1119	    }
1120	}
1121    }
1122    if ((nl = sched_next()) != -1) {
1123	(void) time(&cl);
1124	sched_dif = nl > cl ? nl - cl : 0;
1125	if ((alrm_time == 0) || ((unsigned) sched_dif < alrm_time)) {
1126	    alrm_time = ((unsigned) sched_dif) + 1;
1127	    alm_fun = sched_run;
1128	}
1129    }
1130    alrmcatch_disabled = 0;
1131    (void) alarm(alrm_time);	/* Autologout ON */
1132}
1133
1134#undef RMDEBUG			/* For now... */
1135
1136void
1137rmstar(struct wordent *cp)
1138{
1139    struct wordent *we, *args;
1140    struct wordent *tmp, *del;
1141
1142#ifdef RMDEBUG
1143    static Char STRrmdebug[] = {'r', 'm', 'd', 'e', 'b', 'u', 'g', '\0'};
1144    Char   *tag;
1145#endif /* RMDEBUG */
1146    Char   *charac;
1147    int     ask, doit, star = 0, silent = 0, opintr_disabled;
1148
1149    if (!adrof(STRrmstar))
1150	return;
1151#ifdef RMDEBUG
1152    tag = varval(STRrmdebug);
1153#endif /* RMDEBUG */
1154    we = cp->next;
1155    while (*we->word == ';' && we != cp)
1156	we = we->next;
1157    opintr_disabled = pintr_disabled;
1158    pintr_disabled = 0;
1159    while (we != cp) {
1160#ifdef RMDEBUG
1161	if (*tag)
1162	    xprintf(CGETS(22, 7, "parsing command line\n"));
1163#endif /* RMDEBUG */
1164	if (!Strcmp(we->word, STRrm)) {
1165	    args = we->next;
1166	    ask = (*args->word != '-');
1167	    while (*args->word == '-' && !silent) {	/* check options */
1168		for (charac = (args->word + 1); *charac && !silent; charac++)
1169		    silent = (*charac == 'i' || *charac == 'f');
1170		args = args->next;
1171	    }
1172	    ask = (ask || (!ask && !silent));
1173	    if (ask) {
1174		for (; !star && *args->word != ';'
1175		     && args != cp; args = args->next)
1176		    if (!Strcmp(args->word, STRstar))
1177			star = 1;
1178		if (ask && star) {
1179		    doit = getYN(CGETS(22, 8,
1180			"Do you really want to delete all files? [N/y] "));
1181		    if (!doit) {
1182			/* remove the command instead */
1183#ifdef RMDEBUG
1184			if (*tag)
1185			    xprintf(CGETS(22, 9,
1186				    "skipping deletion of files!\n"));
1187#endif /* RMDEBUG */
1188			for (tmp = we;
1189			     *tmp->word != '\n' &&
1190			     *tmp->word != ';' && tmp != cp;) {
1191			    tmp->prev->next = tmp->next;
1192			    tmp->next->prev = tmp->prev;
1193			    xfree(tmp->word);
1194			    del = tmp;
1195			    tmp = tmp->next;
1196			    xfree(del);
1197			}
1198			if (*tmp->word == ';') {
1199			    tmp->prev->next = tmp->next;
1200			    tmp->next->prev = tmp->prev;
1201			    xfree(tmp->word);
1202			    del = tmp;
1203			    tmp = tmp->next;
1204			    xfree(del);
1205			}
1206			we = tmp;
1207			continue;
1208		    }
1209		}
1210	    }
1211	}
1212	for (we = we->next;
1213	     *we->word != ';' && we != cp;
1214	     we = we->next)
1215	    continue;
1216	if (*we->word == ';')
1217	    we = we->next;
1218    }
1219#ifdef RMDEBUG
1220    if (*tag) {
1221	xprintf(CGETS(22, 10, "command line now is:\n"));
1222	for (we = cp->next; we != cp; we = we->next)
1223	    xprintf("%S ", we->word);
1224    }
1225#endif /* RMDEBUG */
1226    pintr_disabled = opintr_disabled;
1227    return;
1228}
1229
1230#ifdef BSDJOBS
1231/* Check if command is in continue list
1232   and do a "aliasing" if it exists as a job in background */
1233
1234#undef CNDEBUG			/* For now */
1235void
1236continue_jobs(struct wordent *cp)
1237{
1238    struct wordent *we;
1239    struct process *pp, *np;
1240    Char   *cmd, *continue_list, *continue_args_list;
1241
1242#ifdef CNDEBUG
1243    Char   *tag;
1244    static Char STRcndebug[] =
1245    {'c', 'n', 'd', 'e', 'b', 'u', 'g', '\0'};
1246#endif /* CNDEBUG */
1247    int    in_cont_list, in_cont_arg_list;
1248
1249
1250#ifdef CNDEBUG
1251    tag = varval(STRcndebug);
1252#endif /* CNDEBUG */
1253    continue_list = varval(STRcontinue);
1254    continue_args_list = varval(STRcontinue_args);
1255    if (*continue_list == '\0' && *continue_args_list == '\0')
1256	return;
1257
1258    we = cp->next;
1259    while (*we->word == ';' && we != cp)
1260	we = we->next;
1261    while (we != cp) {
1262#ifdef CNDEBUG
1263	if (*tag)
1264	    xprintf(CGETS(22, 11, "parsing command line\n"));
1265#endif /* CNDEBUG */
1266	cmd = we->word;
1267	in_cont_list = inlist(continue_list, cmd);
1268	in_cont_arg_list = inlist(continue_args_list, cmd);
1269	if (in_cont_list || in_cont_arg_list) {
1270#ifdef CNDEBUG
1271	    if (*tag)
1272		xprintf(CGETS(22, 12, "in one of the lists\n"));
1273#endif /* CNDEBUG */
1274	    np = NULL;
1275	    for (pp = proclist.p_next; pp; pp = pp->p_next) {
1276		if (prefix(cmd, pp->p_command)) {
1277		    if (pp->p_index) {
1278			np = pp;
1279			break;
1280		    }
1281		}
1282	    }
1283	    if (np) {
1284		insert(we, in_cont_arg_list);
1285	    }
1286	}
1287	for (we = we->next;
1288	     *we->word != ';' && we != cp;
1289	     we = we->next)
1290	    continue;
1291	if (*we->word == ';')
1292	    we = we->next;
1293    }
1294#ifdef CNDEBUG
1295    if (*tag) {
1296	xprintf(CGETS(22, 13, "command line now is:\n"));
1297	for (we = cp->next; we != cp; we = we->next)
1298	    xprintf("%S ", we->word);
1299    }
1300#endif /* CNDEBUG */
1301    return;
1302}
1303
1304/* The actual "aliasing" of for backgrounds() is done here
1305   with the aid of insert_we().   */
1306static void
1307insert(struct wordent *pl, int file_args)
1308{
1309    struct wordent *now, *last;
1310    Char   *cmd, *bcmd, *cp1, *cp2;
1311    size_t cmd_len;
1312    Char   *upause = STRunderpause;
1313    size_t p_len = Strlen(upause);
1314
1315    cmd_len = Strlen(pl->word);
1316    cmd = xcalloc(1, (cmd_len + 1) * sizeof(Char));
1317    (void) Strcpy(cmd, pl->word);
1318/* Do insertions at beginning, first replace command word */
1319
1320    if (file_args) {
1321	now = pl;
1322	xfree(now->word);
1323	now->word = xcalloc(1, 5 * sizeof(Char));
1324	(void) Strcpy(now->word, STRecho);
1325
1326	now = xcalloc(1, sizeof(struct wordent));
1327	now->word = xcalloc(1, 6 * sizeof(Char));
1328	(void) Strcpy(now->word, STRbackqpwd);
1329	insert_we(now, pl);
1330
1331	for (last = now; *last->word != '\n' && *last->word != ';';
1332	     last = last->next)
1333	    continue;
1334
1335	now = xcalloc(1, sizeof(struct wordent));
1336	now->word = xcalloc(1, 2 * sizeof(Char));
1337	(void) Strcpy(now->word, STRgt);
1338	insert_we(now, last->prev);
1339
1340	now = xcalloc(1, sizeof(struct wordent));
1341	now->word = xcalloc(1, 2 * sizeof(Char));
1342	(void) Strcpy(now->word, STRbang);
1343	insert_we(now, last->prev);
1344
1345	now = xcalloc(1, sizeof(struct wordent));
1346	now->word = xcalloc(1, (cmd_len + p_len + 4) * sizeof(Char));
1347	cp1 = now->word;
1348	cp2 = cmd;
1349	*cp1++ = '~';
1350	*cp1++ = '/';
1351	*cp1++ = '.';
1352	while ((*cp1++ = *cp2++) != '\0')
1353	    continue;
1354	cp1--;
1355	cp2 = upause;
1356	while ((*cp1++ = *cp2++) != '\0')
1357	    continue;
1358	insert_we(now, last->prev);
1359
1360	now = xcalloc(1, sizeof(struct wordent));
1361	now->word = xcalloc(1, 2 * sizeof(Char));
1362	(void) Strcpy(now->word, STRsemi);
1363	insert_we(now, last->prev);
1364	bcmd = xcalloc(1, (cmd_len + 2) * sizeof(Char));
1365	*bcmd = '%';
1366	Strcpy(bcmd + 1, cmd);
1367	now = xcalloc(1, sizeof(struct wordent));
1368	now->word = bcmd;
1369	insert_we(now, last->prev);
1370    }
1371    else {
1372	struct wordent *del;
1373
1374	now = pl;
1375	xfree(now->word);
1376	now->word = xcalloc(1, (cmd_len + 2) * sizeof(Char));
1377	*now->word = '%';
1378	Strcpy(now->word + 1, cmd);
1379	for (now = now->next;
1380	     *now->word != '\n' && *now->word != ';' && now != pl;) {
1381	    now->prev->next = now->next;
1382	    now->next->prev = now->prev;
1383	    xfree(now->word);
1384	    del = now;
1385	    now = now->next;
1386	    xfree(del);
1387	}
1388    }
1389}
1390
1391static void
1392insert_we(struct wordent *new, struct wordent *where)
1393{
1394
1395    new->prev = where;
1396    new->next = where->next;
1397    where->next = new;
1398    new->next->prev = new;
1399}
1400
1401static int
1402inlist(Char *list, Char *name)
1403{
1404    Char *l, *n;
1405
1406    l = list;
1407    n = name;
1408
1409    while (*l && *n) {
1410	if (*l == *n) {
1411	    l++;
1412	    n++;
1413	    if (*n == '\0' && (*l == ' ' || *l == '\0'))
1414		return (1);
1415	    else
1416		continue;
1417	}
1418	else {
1419	    while (*l && *l != ' ')
1420		l++;		/* skip to blank */
1421	    while (*l && *l == ' ')
1422		l++;		/* and find first nonblank character */
1423	    n = name;
1424	}
1425    }
1426    return (0);
1427}
1428
1429#endif /* BSDJOBS */
1430
1431
1432/*
1433 * Implement a small cache for tilde names. This is used primarily
1434 * to expand tilde names to directories, but also
1435 * we can find users from their home directories for the tilde
1436 * prompt, on machines where yp lookup is slow this can be a big win...
1437 * As with any cache this can run out of sync, rehash can sync it again.
1438 */
1439static struct tildecache {
1440    Char   *user;
1441    Char   *home;
1442    size_t  hlen;
1443}      *tcache = NULL;
1444
1445#define TILINCR 10
1446size_t tlength = 0;
1447static size_t tsize = TILINCR;
1448
1449static int
1450tildecompare(const void *xp1, const void *xp2)
1451{
1452    const struct tildecache *p1, *p2;
1453
1454    p1 = xp1;
1455    p2 = xp2;
1456    return Strcmp(p1->user, p2->user);
1457}
1458
1459static Char *
1460gethomedir(const Char *us)
1461{
1462    struct passwd *pp;
1463#ifdef HESIOD
1464    char **res, **res1, *cp;
1465    Char *rp;
1466#endif /* HESIOD */
1467
1468    pp = xgetpwnam(short2str(us));
1469#ifdef YPBUGS
1470    fix_yp_bugs();
1471#endif /* YPBUGS */
1472    if (pp != NULL) {
1473#if 0
1474	/* Don't return if root */
1475	if (pp->pw_dir[0] == '/' && pp->pw_dir[1] == '\0')
1476	    return NULL;
1477	else
1478#endif
1479	    return Strsave(str2short(pp->pw_dir));
1480    }
1481#ifdef HESIOD
1482    res = hes_resolve(short2str(us), "filsys");
1483    rp = NULL;
1484    if (res != NULL) {
1485	if ((*res) != NULL) {
1486	    /*
1487	     * Look at the first token to determine how to interpret
1488	     * the rest of it.
1489	     * Yes, strtok is evil (it's not thread-safe), but it's also
1490	     * easy to use.
1491	     */
1492	    cp = strtok(*res, " ");
1493	    if (strcmp(cp, "AFS") == 0) {
1494		/* next token is AFS pathname.. */
1495		cp = strtok(NULL, " ");
1496		if (cp != NULL)
1497		    rp = Strsave(str2short(cp));
1498	    } else if (strcmp(cp, "NFS") == 0) {
1499		cp = NULL;
1500		if ((strtok(NULL, " ")) && /* skip remote pathname */
1501		    (strtok(NULL, " ")) && /* skip host */
1502		    (strtok(NULL, " ")) && /* skip mode */
1503		    (cp = strtok(NULL, " "))) {
1504		    rp = Strsave(str2short(cp));
1505		}
1506	    }
1507	}
1508	for (res1 = res; *res1; res1++)
1509	    free(*res1);
1510#if 0
1511	/* Don't return if root */
1512	if (rp != NULL && rp[0] == '/' && rp[1] == '\0') {
1513	    xfree(rp);
1514	    rp = NULL;
1515	}
1516#endif
1517	return rp;
1518    }
1519#endif /* HESIOD */
1520    return NULL;
1521}
1522
1523Char   *
1524gettilde(const Char *us)
1525{
1526    struct tildecache *bp1, *bp2, *bp;
1527    Char *hd;
1528
1529    /* Ignore NIS special names */
1530    if (*us == '+' || *us == '-')
1531	return NULL;
1532
1533    if (tcache == NULL)
1534	tcache = xmalloc(TILINCR * sizeof(struct tildecache));
1535    /*
1536     * Binary search
1537     */
1538    for (bp1 = tcache, bp2 = tcache + tlength; bp1 < bp2;) {
1539	int i;
1540
1541	bp = bp1 + ((bp2 - bp1) >> 1);
1542	if ((i = *us - *bp->user) == 0 && (i = Strcmp(us, bp->user)) == 0)
1543	    return (bp->home);
1544	if (i < 0)
1545	    bp2 = bp;
1546	else
1547	    bp1 = bp + 1;
1548    }
1549    /*
1550     * Not in the cache, try to get it from the passwd file
1551     */
1552    hd = gethomedir(us);
1553    if (hd == NULL)
1554	return NULL;
1555
1556    /*
1557     * Update the cache
1558     */
1559    tcache[tlength].user = Strsave(us);
1560    tcache[tlength].home = hd;
1561    tcache[tlength++].hlen = Strlen(hd);
1562
1563    qsort(tcache, tlength, sizeof(struct tildecache), tildecompare);
1564
1565    if (tlength == tsize) {
1566	tsize += TILINCR;
1567	tcache = xrealloc(tcache, tsize * sizeof(struct tildecache));
1568    }
1569    return (hd);
1570}
1571
1572/*
1573 * Return the username if the directory path passed contains a
1574 * user's home directory in the tilde cache, otherwise return NULL
1575 * hm points to the place where the path became different.
1576 * Special case: Our own home directory.
1577 * If we are passed a null pointer, then we flush the cache.
1578 */
1579Char   *
1580getusername(Char **hm)
1581{
1582    Char   *h, *p;
1583    size_t i, j;
1584
1585    if (hm == NULL) {
1586	for (i = 0; i < tlength; i++) {
1587	    xfree(tcache[i].home);
1588	    xfree(tcache[i].user);
1589	}
1590	xfree(tcache);
1591	tlength = 0;
1592	tsize = TILINCR;
1593	tcache = NULL;
1594	return NULL;
1595    }
1596    p = *hm;
1597    if (((h = varval(STRhome)) != STRNULL) &&
1598	(Strncmp(p, h, j = Strlen(h)) == 0) &&
1599	(p[j] == '/' || p[j] == '\0')) {
1600	*hm = &p[j];
1601	return STRNULL;
1602    }
1603    for (i = 0; i < tlength; i++)
1604	if ((Strncmp(p, tcache[i].home, (j = tcache[i].hlen)) == 0) &&
1605	    (p[j] == '/' || p[j] == '\0')) {
1606	    *hm = &p[j];
1607	    return tcache[i].user;
1608	}
1609    return NULL;
1610}
1611
1612
1613/*
1614 * set the shell-level var to 1 or apply change to it.
1615 */
1616void
1617shlvl(int val)
1618{
1619    char *cp;
1620
1621    if ((cp = getenv("SHLVL")) != NULL) {
1622
1623	if (loginsh)
1624	    val = 1;
1625	else
1626	    val += atoi(cp);
1627
1628	if (val <= 0) {
1629	    if (adrof(STRshlvl) != NULL)
1630		unsetv(STRshlvl);
1631	    Unsetenv(STRKSHLVL);
1632	}
1633	else {
1634	    Char *p;
1635
1636	    p = Itoa(val, 0, 0);
1637	    cleanup_push(p, xfree);
1638	    setv(STRshlvl, p, VAR_READWRITE);
1639	    cleanup_ignore(p);
1640	    cleanup_until(p);
1641	    tsetenv(STRKSHLVL, p);
1642	}
1643    }
1644    else {
1645	setcopy(STRshlvl, STR1, VAR_READWRITE);
1646	tsetenv(STRKSHLVL, STR1);
1647    }
1648}
1649
1650
1651/* fixio():
1652 *	Try to recover from a read error
1653 */
1654int
1655fixio(int fd, int e)
1656{
1657    switch (e) {
1658    case -1:	/* Make sure that the code is reachable */
1659
1660#ifdef EWOULDBLOCK
1661    case EWOULDBLOCK:
1662# define FDRETRY
1663#endif /* EWOULDBLOCK */
1664
1665#if defined(POSIX) && defined(EAGAIN)
1666# if !defined(EWOULDBLOCK) || EWOULDBLOCK != EAGAIN
1667    case EAGAIN:
1668#  define FDRETRY
1669# endif /* !EWOULDBLOCK || EWOULDBLOCK != EAGAIN */
1670#endif /* POSIX && EAGAIN */
1671
1672	e = -1;
1673#ifdef FDRETRY
1674# ifdef F_SETFL
1675/*
1676 * Great! we have on suns 3 flavors and 5 names...
1677 * I hope that will cover everything.
1678 * I added some more defines... many systems have different defines.
1679 * Rather than dealing with getting the right includes, we'll just
1680 * cover all the known possibilities here.  -- sterling@netcom.com
1681 */
1682#  ifndef O_NONBLOCK
1683#   define O_NONBLOCK 0
1684#  endif /* O_NONBLOCK */
1685#  ifndef O_NDELAY
1686#   define O_NDELAY 0
1687#  endif /* O_NDELAY */
1688#  ifndef FNBIO
1689#   define FNBIO 0
1690#  endif /* FNBIO */
1691#  ifndef _FNBIO
1692#   define _FNBIO 0
1693#  endif /* _FNBIO */
1694#  ifndef FNONBIO
1695#   define FNONBIO 0
1696#  endif /* FNONBIO */
1697#  ifndef FNONBLOCK
1698#   define FNONBLOCK 0
1699#  endif /* FNONBLOCK */
1700#  ifndef _FNONBLOCK
1701#   define _FNONBLOCK 0
1702#  endif /* _FNONBLOCK */
1703#  ifndef FNDELAY
1704#   define FNDELAY 0
1705#  endif /* FNDELAY */
1706#  ifndef _FNDELAY
1707#   define _FNDELAY 0
1708#  endif /* _FNDELAY */
1709#  ifndef FNDLEAY	/* Some linux versions have this typo */
1710#   define FNDLEAY 0
1711#  endif /* FNDLEAY */
1712	if ((e = fcntl(fd, F_GETFL, 0)) == -1)
1713	    return -1;
1714
1715	e &= ~(O_NDELAY|O_NONBLOCK|FNBIO|_FNBIO|FNONBIO|FNONBLOCK|_FNONBLOCK|
1716	       FNDELAY|_FNDELAY|FNDLEAY);	/* whew! */
1717	if (fcntl(fd, F_SETFL, e) == -1)
1718	    return -1;
1719	else
1720	    e = 0;
1721# endif /* F_SETFL */
1722
1723# ifdef FIONBIO
1724	e = 0;
1725	if (ioctl(fd, FIONBIO, (ioctl_t) &e) == -1)
1726	    return -1;
1727# endif	/* FIONBIO */
1728
1729#endif /* FDRETRY */
1730	return e;
1731
1732    case EINTR:
1733	return 0;
1734
1735    default:
1736	return -1;
1737    }
1738}
1739
1740/* collate():
1741 *	String collation
1742 */
1743int
1744collate(const Char *a, const Char *b)
1745{
1746    int rv;
1747#ifdef SHORT_STRINGS
1748    /* This strips the quote bit as a side effect */
1749    char *sa = strsave(short2str(a));
1750    char *sb = strsave(short2str(b));
1751#else
1752    char *sa = strip(strsave(a));
1753    char *sb = strip(strsave(b));
1754#endif /* SHORT_STRINGS */
1755
1756#if defined(NLS) && defined(HAVE_STRCOLL)
1757    errno = 0;	/* strcoll sets errno, another brain-damage */
1758
1759    rv = strcoll(sa, sb);
1760
1761    /*
1762     * We should be checking for errno != 0, but some systems
1763     * forget to reset errno to 0. So we only check for the
1764     * only documented valid errno value for strcoll [EINVAL]
1765     */
1766    if (errno == EINVAL) {
1767	xfree(sa);
1768	xfree(sb);
1769	stderror(ERR_SYSTEM, "strcoll", strerror(errno));
1770    }
1771#else
1772    rv = strcmp(sa, sb);
1773#endif /* NLS && HAVE_STRCOLL */
1774
1775    xfree(sa);
1776    xfree(sb);
1777
1778    return rv;
1779}
1780
1781#ifdef HASHBANG
1782/*
1783 * From: peter@zeus.dialix.oz.au (Peter Wemm)
1784 * If exec() fails look first for a #! [word] [word] ....
1785 * If it is, splice the header into the argument list and retry.
1786 */
1787#define HACKBUFSZ 1024		/* Max chars in #! vector */
1788int
1789hashbang(int fd, Char ***vp)
1790{
1791    struct blk_buf sarg = BLK_BUF_INIT;
1792    char lbuf[HACKBUFSZ], *p, *ws;
1793#ifdef WINNT_NATIVE
1794    int fw = 0; 	/* found at least one word */
1795    int first_word = 1;
1796    char *real;
1797#endif /* WINNT_NATIVE */
1798
1799    if (xread(fd, lbuf, HACKBUFSZ) <= 0)
1800	return -1;
1801
1802    ws = 0;	/* word started = 0 */
1803
1804    for (p = lbuf; p < &lbuf[HACKBUFSZ]; ) {
1805	switch (*p) {
1806	case ' ':
1807	case '\t':
1808#if defined(WINNT_NATIVE) || defined (__CYGWIN__)
1809	case '\r':
1810#endif /* WINNT_NATIVE || __CYGWIN__ */
1811	    if (ws) {	/* a blank after a word.. save it */
1812		*p = '\0';
1813#ifdef WINNT_NATIVE
1814		if (first_word) {
1815		    real = hb_subst(ws);
1816		    if (real != NULL)
1817			ws = real;
1818		}
1819	    	fw = 1;
1820		first_word = 0;
1821#endif /* WINNT_NATIVE */
1822		bb_append(&sarg, SAVE(ws));
1823		ws = NULL;
1824	    }
1825	    p++;
1826	    continue;
1827
1828	case '\0':	/* Whoa!! what the hell happened */
1829	    goto err;
1830
1831	case '\n':	/* The end of the line. */
1832	    if (
1833#ifdef WINNT_NATIVE
1834		fw ||
1835#endif /* WINNT_NATIVE */
1836		ws) {	/* terminate the last word */
1837		*p = '\0';
1838#ifdef WINNT_NATIVE
1839		/* deal with the 1-word case */
1840		if (first_word) {
1841		    real = hb_subst(ws);
1842		    if (real != NULL)
1843			ws = real;
1844		}
1845#endif /* !WINNT_NATIVE */
1846		if (ws)
1847		    bb_append(&sarg, SAVE(ws));
1848	    }
1849	    if (sarg.len > 0) {
1850		*vp = bb_finish(&sarg);
1851		return 0;
1852	    }
1853	    else
1854		goto err;
1855
1856	default:
1857	    if (!ws)	/* Start a new word? */
1858		ws = p;
1859	    p++;
1860	    break;
1861	}
1862    }
1863 err:
1864    bb_cleanup(&sarg);
1865    return -1;
1866}
1867#endif /* HASHBANG */
1868
1869#ifdef REMOTEHOST
1870
1871static void
1872palarm(int snum)
1873{
1874    USE(snum);
1875    _exit(1);
1876}
1877
1878static void
1879getremotehost(int dest_fd)
1880{
1881    const char *host = NULL;
1882#ifdef INET6
1883    struct sockaddr_storage saddr;
1884    static char hbuf[NI_MAXHOST];
1885#else
1886    struct hostent* hp;
1887    struct sockaddr_in saddr;
1888#endif
1889    socklen_t len = sizeof(saddr);
1890
1891#ifdef INET6
1892    if (getpeername(SHIN, (struct sockaddr *) &saddr, &len) != -1 &&
1893	(saddr.ss_family == AF_INET6 || saddr.ss_family == AF_INET)) {
1894	int flag = NI_NUMERICHOST;
1895
1896#ifdef NI_WITHSCOPEID
1897	flag |= NI_WITHSCOPEID;
1898#endif
1899	getnameinfo((struct sockaddr *)&saddr, len, hbuf, sizeof(hbuf),
1900		    NULL, 0, flag);
1901	host = hbuf;
1902#else
1903    if (getpeername(SHIN, (struct sockaddr *) &saddr, &len) != -1 &&
1904	saddr.sin_family == AF_INET) {
1905#if 0
1906	if ((hp = gethostbyaddr((char *)&saddr.sin_addr, sizeof(struct in_addr),
1907				AF_INET)) != NULL)
1908	    host = hp->h_name;
1909	else
1910#endif
1911	    host = inet_ntoa(saddr.sin_addr);
1912#endif
1913    }
1914#ifdef HAVE_STRUCT_UTMP_UT_HOST
1915    else {
1916	char *ptr;
1917	char *name = utmphost();
1918	/* Avoid empty names and local X displays */
1919	if (name != NULL && *name != '\0' && *name != ':') {
1920	    struct in_addr addr;
1921	    char *sptr;
1922
1923	    /* Look for host:display.screen */
1924	    /*
1925	     * There is conflict with IPv6 address and X DISPLAY.  So,
1926	     * we assume there is no IPv6 address in utmp and don't
1927	     * touch here.
1928	     */
1929	    if ((sptr = strchr(name, ':')) != NULL)
1930		*sptr = '\0';
1931	    /* Leave IPv4 address as is */
1932	    /*
1933	     * we use inet_addr here, not inet_aton because many systems
1934	     * have not caught up yet.
1935	     */
1936	    addr.s_addr = inet_addr(name);
1937	    if (addr.s_addr != (unsigned int)~0)
1938		host = name;
1939	    else {
1940		if (sptr != name) {
1941#ifdef INET6
1942		    char *s, *domain;
1943		    char dbuf[MAXHOSTNAMELEN];
1944		    struct addrinfo hints, *res = NULL;
1945
1946		    memset(&hints, 0, sizeof(hints));
1947		    hints.ai_family = PF_UNSPEC;
1948		    hints.ai_socktype = SOCK_STREAM;
1949		    hints.ai_flags = AI_PASSIVE | AI_CANONNAME;
1950		    if (strlen(name) < utmphostsize())
1951		    {
1952			if (getaddrinfo(name, NULL, &hints, &res) != 0)
1953			    res = NULL;
1954		    } else if (gethostname(dbuf, sizeof(dbuf)) == 0 &&
1955			       (dbuf[sizeof(dbuf)-1] = '\0', /*FIXME: ugly*/
1956				(domain = strchr(dbuf, '.')) != NULL)) {
1957			for (s = strchr(name, '.');
1958			     s != NULL; s = strchr(s + 1, '.')) {
1959			    if (*(s + 1) != '\0' &&
1960				(ptr = strstr(domain, s)) != NULL) {
1961			        char *cbuf;
1962
1963				cbuf = strspl(name, ptr + strlen(s));
1964				if (getaddrinfo(cbuf, NULL, &hints, &res) != 0)
1965				    res = NULL;
1966				xfree(cbuf);
1967				break;
1968			    }
1969			}
1970		    }
1971		    if (res != NULL) {
1972			if (res->ai_canonname != NULL) {
1973			    strncpy(hbuf, res->ai_canonname, sizeof(hbuf));
1974			    hbuf[sizeof(hbuf) - 1] = '\0';
1975			    host = hbuf;
1976			}
1977			freeaddrinfo(res);
1978		    }
1979#else
1980		    if ((hp = gethostbyname(name)) == NULL) {
1981			/* Try again eliminating the trailing domain */
1982			if ((ptr = strchr(name, '.')) != NULL) {
1983			    *ptr = '\0';
1984			    if ((hp = gethostbyname(name)) != NULL)
1985				host = hp->h_name;
1986			    *ptr = '.';
1987			}
1988		    }
1989		    else
1990			host = hp->h_name;
1991#endif
1992		}
1993	    }
1994	}
1995    }
1996#endif
1997
1998    if (host) {
1999	size_t left;
2000
2001	left = strlen(host);
2002	while (left != 0) {
2003	    ssize_t res;
2004
2005	    res = xwrite(dest_fd, host, left);
2006	    if (res < 0)
2007		_exit(1);
2008	    host += res;
2009	    left -= res;
2010	}
2011    }
2012    _exit(0);
2013}
2014
2015/*
2016 * From: <lesv@ppvku.ericsson.se> (Lennart Svensson)
2017 */
2018void
2019remotehost(void)
2020{
2021    struct sigaction sa;
2022    struct strbuf hostname = strbuf_INIT;
2023    int fds[2], wait_options, status;
2024    pid_t pid, wait_res;
2025
2026    sa.sa_handler = SIG_DFL; /* Make sure a zombie is created */
2027    sigemptyset(&sa.sa_mask);
2028    sa.sa_flags = 0;
2029    sigaction(SIGCHLD, &sa, NULL);
2030    mypipe(fds);
2031    pid = fork();
2032    if (pid == 0) {
2033	sigset_t set;
2034	xclose(fds[0]);
2035	/* Don't get stuck if the resolver does not work! */
2036	signal(SIGALRM, palarm);
2037	sigemptyset(&set);
2038	sigaddset(&set, SIGALRM);
2039	(void)sigprocmask(SIG_UNBLOCK, &set, NULL);
2040	(void)alarm(2);
2041	getremotehost(fds[1]);
2042	/*NOTREACHED*/
2043    }
2044    xclose(fds[1]);
2045    for (;;) {
2046	char buf[BUFSIZE];
2047	ssize_t res;
2048
2049	res = xread(fds[0], buf, sizeof(buf));
2050	if (res == -1) {
2051	    hostname.len = 0;
2052	    wait_options = WNOHANG;
2053	    goto done;
2054	}
2055	if (res == 0)
2056	    break;
2057	strbuf_appendn(&hostname, buf, res);
2058    }
2059    wait_options = 0;
2060 done:
2061    cleanup_push(&hostname, strbuf_cleanup);
2062    xclose(fds[0]);
2063    while ((wait_res = waitpid(pid, &status, wait_options)) == -1
2064	   && errno == EINTR)
2065	handle_pending_signals();
2066    if (hostname.len > 0 && wait_res == pid && WIFEXITED(status)
2067	   && WEXITSTATUS(status) == 0) {
2068	strbuf_terminate(&hostname);
2069	tsetenv(STRREMOTEHOST, str2short(hostname.s));
2070    }
2071    cleanup_until(&hostname);
2072
2073#ifdef YPBUGS
2074    /* From: casper@fwi.uva.nl (Casper H.S. Dik), for Solaris 2.3 */
2075    fix_yp_bugs();
2076#endif /* YPBUGS */
2077
2078}
2079#endif /* REMOTEHOST */
2080
2081#ifndef WINNT_NATIVE
2082/*
2083 * indicate if a terminal type is defined in terminfo/termcap
2084 * (by default the current term type). This allows ppl to look
2085 * for a working term type automatically in their login scripts
2086 * when using a terminal known as different things on different
2087 * platforms
2088 */
2089void
2090dotermname(Char **v, struct command *c)
2091{
2092    char *termtype;
2093    /*
2094     * Maximum size of a termcap record. We make it twice as large.
2095     */
2096    char termcap_buffer[2048];
2097
2098    USE(c);
2099    /* try to find which entry we should be looking for */
2100    termtype = (v[1] == NULL ? getenv("TERM") : short2str(v[1]));
2101    if (termtype == NULL) {
2102	/* no luck - the user didn't provide one and none is
2103	 * specified in the environment
2104	 */
2105	setcopy(STRstatus, STR1, VAR_READWRITE);
2106	return;
2107    }
2108
2109    /*
2110     * we use the termcap function - if we are using terminfo we
2111     * will end up with it's compatibility function
2112     * terminfo/termcap will be initialized with the new
2113     * type but we don't care because tcsh has cached all the things
2114     * it needs.
2115     */
2116    if (tgetent(termcap_buffer, termtype) == 1) {
2117	xprintf("%s\n", termtype);
2118	setcopy(STRstatus, STR0, VAR_READWRITE);
2119    } else
2120	setcopy(STRstatus, STR1, VAR_READWRITE);
2121}
2122#endif /* WINNT_NATIVE */
2123