1 /* $Header: /p/tcsh/cvsroot/tcsh/tc.func.c,v 3.148 2011/12/14 16:36:44 christos Exp $ */
3 * tc.func.c: New tcsh builtins.
6 * Copyright (c) 1980, 1991 The Regents of the University of California.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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.
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
35 RCSID("$tcsh: tc.func.c,v 3.148 2011/12/14 16:36:44 christos Exp $")
38 #include "ed.defns.h" /* for the function names */
43 #else /* WINNT_NATIVE */
45 #endif /* WINNT_NATIVE */
49 #include <afs/kautils.h>
50 long ka_UserAuthenticateGeneral();
56 extern time_t t_period;
57 extern int just_signaled;
58 static int precmd_active = 0;
59 static int jobcmd_active = 0; /* GrP */
60 static int postcmd_active = 0;
61 static int periodic_active = 0;
62 static int cwdcmd_active = 0; /* PWP: for cwd_cmd */
63 static int beepcmd_active = 0;
64 static void (*alm_fun)(void) = NULL;
66 static void auto_logout (void);
67 static char *xgetpass (const char *);
68 static void auto_lock (void);
70 static void insert (struct wordent *, int);
71 static void insert_we (struct wordent *, struct wordent *);
72 static int inlist (Char *, Char *);
74 static int tildecompare (const void *, const void *);
75 static Char *gethomedir (const Char *);
77 static void palarm (int);
78 static void getremotehost (int);
79 #endif /* REMOTEHOST */
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
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
95 /* PWP: this is a combination of the old sprlex() and the expand_lex from
96 the magic-space stuff */
99 expand_lex(const struct wordent *sp0, int from, int to)
101 struct Strbuf buf = Strbuf_INIT;
102 const struct wordent *sp;
109 if (!sp0 || (sp = sp0->next) == sp0 || sp == (sp0 = sp0->prev))
110 return Strbuf_finish(&buf); /* null lex */
113 if ((i >= from) && (i <= to)) { /* if in range */
114 for (s = sp->word; *s; s++) {
116 * bugfix by Michael Bloom: anything but the current history
117 * character {(PWP) and backslash} seem to be dealt with
121 && (((*s & TRIM) == HIST && HIST != '\0') ||
122 (((*s & TRIM) == '\'') && (prev_c != '\\')) ||
123 (((*s & TRIM) == '\"') && (prev_c != '\\')) ||
124 (((*s & TRIM) == '\\') && (prev_c != '\\')))) {
125 Strbuf_append1(&buf, '\\');
127 Strbuf_append1(&buf, *s & TRIM);
130 Strbuf_append1(&buf, ' ');
137 buf.len--; /* get rid of trailing space */
139 return Strbuf_finish(&buf);
143 sprlex(const struct wordent *sp0)
145 return expand_lex(sp0, 0, INT_MAX);
150 Itoa(int n, size_t min_digits, Char attributes)
153 * The array size here is derived from
155 * which is guaranteed to be enough for a decimal
156 * representation. We add 1 because integer divide
162 Char buf[CHAR_BIT * sizeof(int) / 3 + 1], *res, *p, *s;
163 unsigned int un; /* handle most negative # too */
164 int pad = (min_digits != 0);
166 if (sizeof(buf) - 1 < min_digits)
167 min_digits = sizeof(buf) - 1;
175 *p++ = un % 10 + '0';
177 } while ((pad && (ssize_t)--min_digits > 0) || un != 0);
179 res = xmalloc((p - buf + 2) * sizeof(*res));
184 *s++ = *--p | attributes;
193 dolist(Char **v, struct command *c)
201 struct Strbuf word = Strbuf_INIT;
203 Strbuf_terminate(&word);
204 cleanup_push(&word, Strbuf_cleanup);
205 (void) t_search(&word, LIST, TW_ZERO, 0, STRNULL, 0);
206 cleanup_until(&word);
209 v = glob_all_or_error(v);
211 cleanup_push(globbed, blk_cleanup);
212 for (k = 0; v[k] != NULL && v[k][0] != '-'; k++)
216 * We cannot process a flag therefore we let ls do it right.
220 struct wordent cmd, *nextword, *lastword;
226 cleanup_push(&pintr_disabled, disabled_cleanup);
236 /* Look at listflags, to add -A to the flags, to get a path
237 of ls if necessary */
238 if ((vp = adrof(STRlistflags)) != NULL && vp->vec != NULL &&
239 vp->vec[0] != STRNULL) {
240 if (vp->vec[1] != NULL && vp->vec[1][0] != '\0')
242 for (cp = vp->vec[0]; *cp; cp++)
260 nextword = xcalloc(1, sizeof cmd);
261 nextword->word = Strsave(lspath);
262 lastword->next = nextword;
263 nextword->prev = lastword;
265 nextword = xcalloc(1, sizeof cmd);
266 nextword->word = Strsave(STRmCF);
267 lastword->next = nextword;
268 nextword->prev = lastword;
269 #if defined(KANJI) && defined(SHORT_STRINGS) && defined(DSPMBYTE)
272 nextword = xcalloc(1, sizeof cmd);
273 nextword->word = Strsave(STRmmliteral);
274 lastword->next = nextword;
275 nextword->prev = lastword;
279 if (color_context_ls) {
281 nextword = xcalloc(1, sizeof cmd);
282 nextword->word = Strsave(STRmmcolormauto);
283 lastword->next = nextword;
284 nextword->prev = lastword;
286 #endif /* COLOR_LS_F */
288 for (cp = *v; cp; cp = *++v) {
289 nextword = xcalloc(1, sizeof cmd);
290 nextword->word = quote(Strsave(cp));
291 lastword->next = nextword;
292 nextword->prev = lastword;
295 lastword->next = &cmd;
297 cleanup_push(&cmd, lex_cleanup);
299 /* build a syntax tree for the command. */
300 t = syntax(cmd.next, &cmd, 0);
301 cleanup_push(t, syntax_cleanup);
304 /* expand aliases like process() does */
306 /* execute the parse tree. */
307 execute(t, tpgrp > 0 ? tpgrp : -1, NULL, NULL, FALSE);
308 /* done. free the lex list and parse tree. */
311 cleanup_until(&pintr_disabled);
315 struct Strbuf buf = Strbuf_INIT;
317 cleanup_push(&buf, Strbuf_cleanup);
318 for (k = 0, i = 0; v[k] != NULL; k++) {
319 tmp = dnormalize(v[k], symlinks == SYM_IGNORE);
320 cleanup_push(tmp, xfree);
321 dp = Strend(tmp) - 1;
322 if (*dp == '/' && dp != tmp)
327 if (stat(short2str(tmp), &st) == -1) {
334 print_by_column(STRNULL, &v[i], k - i, FALSE);
336 xprintf("%S: %s.\n", tmp, strerror(err));
339 else if (S_ISDIR(st.st_mode)) {
345 print_by_column(STRNULL, &v[i], k - i, FALSE);
347 if (k != 0 && v[1] != NULL)
349 xprintf("%S:\n", tmp);
351 for (cp = tmp; *cp; cp++)
352 Strbuf_append1(&buf, (*cp | QUOTE));
353 Strbuf_terminate(&buf);
354 dp = &buf.s[buf.len - 1];
357 (*dp != (Char) (':' | QUOTE)) &&
358 #endif /* WINNT_NATIVE */
359 (*dp != (Char) ('/' | QUOTE))) {
360 Strbuf_append1(&buf, '/');
361 Strbuf_terminate(&buf);
364 (void) t_search(&buf, LIST, TW_ZERO, 0, STRNULL, 0);
373 print_by_column(STRNULL, &v[i], k - i, FALSE);
377 cleanup_until(globbed);
380 extern int GotTermCaps;
384 dotelltc(Char **v, struct command *c)
395 doechotc(Char **v, struct command *c)
405 dosettc(Char **v, struct command *c)
413 tv[0] = strsave(short2str(v[1]));
414 cleanup_push(tv[0], xfree);
415 tv[1] = strsave(short2str(v[2]));
416 cleanup_push(tv[1], xfree);
418 cleanup_until(tv[0]);
421 /* The dowhich() is by:
422 * Andreas Luik <luik@isaak.isa.de>
423 * I S A GmbH - Informationssysteme fuer computerintegrierte Automatisierung
430 cmd_expand(Char *cmd, Char **str)
432 struct wordent lexp[3];
436 lexp[0].next = &lexp[1];
437 lexp[1].next = &lexp[2];
438 lexp[2].next = &lexp[0];
440 lexp[0].prev = &lexp[2];
441 lexp[1].prev = &lexp[0];
442 lexp[2].prev = &lexp[1];
444 lexp[0].word = STRNULL;
445 lexp[2].word = STRret;
447 if ((vp = adrof1(cmd, &aliases)) != NULL && vp->vec != NULL) {
449 xprintf(CGETS(22, 1, "%S: \t aliased to "), cmd);
454 *str = blkexpand(vp->vec);
458 rv = tellmewhat(lexp, str);
466 dowhich(Char **v, struct command *c)
472 * We don't want to glob dowhich args because we lose quoteing
473 * E.g. which \ls if ls is aliased will not work correctly if
478 rv &= cmd_expand(*v, NULL);
481 setcopy(STRstatus, STR1, VAR_READWRITE);
484 /* PWP: a hack to start up your stopped editor on a single keystroke */
485 /* jbs - fixed hack so it worked :-) 3/28/89 */
490 struct process *pp, *retp;
496 if ((ep = getenv("EDITOR")) != NULL) { /* if we have a value */
497 if ((p = strrchr(ep, '/')) != NULL) /* if it has a path */
498 ep = p + 1; /* then we want only the last part */
503 if ((vp = getenv("VISUAL")) != NULL) { /* if we have a value */
504 if ((p = strrchr(vp, '/')) != NULL) /* and it has a path */
505 vp = p + 1; /* then we want only the last part */
510 for (vpl = 0; vp[vpl] && !isspace((unsigned char)vp[vpl]); vpl++)
512 for (epl = 0; ep[epl] && !isspace((unsigned char)ep[epl]); epl++)
515 if (pcurrent == NULL) /* see if we have any jobs */
516 return NULL; /* nope */
519 for (pp = proclist.p_next; pp; pp = pp->p_next)
520 if (pp->p_procid == pp->p_jobid) {
523 * Only foreground an edit session if it is suspended. Some GUI
524 * editors have may be happily running in a separate window, no
525 * point in foregrounding these if they're already running - webb
527 pstatus = (int) (pp->p_flags & PALLSTATES);
528 if (pstatus != PINTERRUPTED && pstatus != PSTOPPED &&
529 pstatus != PSIGNALED)
532 p = short2str(pp->p_command);
533 /* get the first word */
534 for (cp = p; *cp && !isspace((unsigned char) *cp); cp++)
538 if ((cp = strrchr(p, '/')) != NULL) /* and it has a path */
539 cp = cp + 1; /* then we want only the last part */
541 cp = p; /* else we get all of it */
543 /* if we find either in the current name, fg it */
544 if (strncmp(ep, cp, epl) == 0 ||
545 strncmp(vp, cp, vpl) == 0) {
548 * If there is a choice, then choose the current process if
549 * available, or the previous process otherwise, or else
550 * anything will do - Robert Webb (robertw@mulga.cs.mu.oz.au).
554 else if (retp == NULL || pp == pprevious)
559 return retp; /* Will be NULL if we didn't find a job */
563 fg_proc_entry(struct process *pp)
573 oGettingInput = GettingInput;
576 ohaderr = haderr; /* we need to ignore setting of haderr due to
577 * process getting stopped by a signal */
578 omark = cleanup_push_mark();
579 if (setexit() == 0) { /* come back here after pjwait */
581 (void) alarm(0); /* No autologout */
582 alrmcatch_disabled = 1;
583 if (!pstart(pp, 1)) {
585 stderror(ERR_BADJOB, pp->p_command, strerror(errno));
589 setalarm(1); /* Autologout back on */
590 cleanup_pop_mark(omark);
593 GettingInput = oGettingInput;
595 disabled_cleanup(&pintr_disabled);
599 xgetpass(const char *prm)
601 static struct strbuf pass; /* = strbuf_INIT; */
604 struct sigaction sa, osa;
606 sa.sa_handler = SIG_IGN;
607 sigemptyset(&sa.sa_mask);
609 (void)sigaction(SIGINT, &sa, &osa);
612 sigaddset(&set, SIGINT);
613 (void)sigprocmask(SIG_UNBLOCK, &set, &oset);
615 cleanup_push(&osa, sigint_cleanup);
616 cleanup_push(&oset, sigprocmask_cleanup);
617 (void) Rawmode(); /* Make sure, cause we want echo off */
618 fd = xopen("/dev/tty", O_RDWR|O_LARGEFILE);
622 cleanup_push(&fd, open_cleanup);
624 xprintf("%s", prm); flush();
629 if (xread(fd, &c, 1) < 1 || c == '\n')
631 strbuf_append1(&pass, c);
633 strbuf_terminate(&pass);
642 extern char *crypt ();
650 * Ask the user for his login password to continue working
651 * On systems that have a shadow password, this will only
652 * work for root, but what can we do?
654 * If we fail to get the password, then we log the user out
669 #if defined(HAVE_AUTH_H) && defined(HAVE_GETAUTHUID)
671 struct authorization *apw;
672 extern char *crypt16 (const char *, const char *);
674 # define XCRYPT(pw, a, b) crypt16(a, b)
676 if ((pw = xgetpwuid(euid)) != NULL && /* effective user passwd */
677 (apw = getauthuid(euid)) != NULL) /* enhanced ultrix passwd */
678 srpp = apw->a_password;
680 #elif defined(HAVE_SHADOW_H)
684 # define XCRYPT(pw, a, b) crypt(a, b)
686 if ((pw = xgetpwuid(euid)) != NULL) { /* effective user passwd */
688 while ((spw = getspnam(pw->pw_name)) == NULL && errno == EINTR) {
689 handle_pending_signals();
692 if (spw != NULL) /* shadowed passwd */
700 # define XCRYPT(pw, a, b) cygwin_xcrypt(pw, a, b)
702 # define XCRYPT(pw, a, b) crypt(a, b)
705 #if !defined(__MVS__)
706 if ((pw = xgetpwuid(euid)) != NULL) /* effective user passwd */
707 srpp = pw->pw_passwd;
718 setalarm(0); /* Not for locking any more */
720 for (i = 0; i < 5; i++) {
727 if ((safs = varval(STRafsuser)) != STRNULL)
728 afsname = short2str(safs);
730 if ((afsname = getenv("AFSUSER")) == NULL)
731 afsname = pw->pw_name;
733 pp = xgetpass("Password:");
735 crpp = XCRYPT(pw, pp, srpp);
736 if ((strcmp(crpp, srpp) == 0)
738 || (ka_UserAuthenticateGeneral(KA_USERAUTH_VERSION,
749 (void) memset(pp, 0, strlen(pp));
750 if (GettingInput && !just_signaled) {
759 xprintf(CGETS(22, 2, "\nIncorrect passwd for %s\n"), pw->pw_name);
761 #endif /* NO_CRYPT */
769 xprintf("auto-logout\n");
770 /* Don't leave the tty in raw mode */
774 setcopy(STRlogout, STRautomatic, VAR_READWRITE);
779 GettingInput = FALSE; /* make flush() work to write hist files. Huber*/
791 * Karl Kleinpaste, 21oct1983.
792 * Added precmd(), which checks for the alias
793 * precmd in aliases. If it's there, the alias
794 * is executed as a command. This is done
795 * after mailchk() and just before print-
796 * ing the prompt. Useful for things like printing
797 * one's current directory just before each command.
803 cleanup_push(&pintr_disabled, disabled_cleanup);
804 if (precmd_active) { /* an error must have been caught */
805 aliasrun(2, STRunalias, STRprecmd);
806 xprintf("%s", CGETS(22, 3, "Faulty alias 'precmd' removed.\n"));
810 if (!whyles && adrof1(STRprecmd, &aliases))
811 aliasrun(1, STRprecmd, NULL);
814 cleanup_until(&pintr_disabled);
821 cleanup_push(&pintr_disabled, disabled_cleanup);
822 if (postcmd_active) { /* an error must have been caught */
823 aliasrun(2, STRunalias, STRpostcmd);
824 xprintf("%s", CGETS(22, 3, "Faulty alias 'postcmd' removed.\n"));
828 if (!whyles && adrof1(STRpostcmd, &aliases))
829 aliasrun(1, STRpostcmd, NULL);
832 cleanup_until(&pintr_disabled);
836 * Paul Placeway 11/24/87 Added cwd_cmd by hacking precmd() into
837 * submission... Run every time $cwd is set (after it is set). Useful
838 * for putting your machine and cwd (or anything else) in an xterm title
845 cleanup_push(&pintr_disabled, disabled_cleanup);
846 if (cwdcmd_active) { /* an error must have been caught */
847 aliasrun(2, STRunalias, STRcwdcmd);
848 xprintf("%s", CGETS(22, 4, "Faulty alias 'cwdcmd' removed.\n"));
852 if (!whyles && adrof1(STRcwdcmd, &aliases))
853 aliasrun(1, STRcwdcmd, NULL);
856 cleanup_until(&pintr_disabled);
860 * Joachim Hoenig 07/16/91 Added beep_cmd, run every time tcsh wishes
861 * to beep the terminal bell. Useful for playing nice sounds instead.
867 cleanup_push(&pintr_disabled, disabled_cleanup);
868 if (beepcmd_active) { /* an error must have been caught */
869 aliasrun(2, STRunalias, STRbeepcmd);
870 xprintf("%s", CGETS(22, 5, "Faulty alias 'beepcmd' removed.\n"));
874 if (!whyles && adrof1(STRbeepcmd, &aliases))
875 aliasrun(1, STRbeepcmd, NULL);
878 cleanup_until(&pintr_disabled);
883 * Karl Kleinpaste, 18 Jan 1984.
884 * Added period_cmd(), which executes the alias "periodic" every
885 * $tperiod minutes. Useful for occasional checking of msgs and such.
894 cleanup_push(&pintr_disabled, disabled_cleanup);
895 if (periodic_active) { /* an error must have been caught */
896 aliasrun(2, STRunalias, STRperiodic);
897 xprintf("%s", CGETS(22, 6, "Faulty alias 'periodic' removed.\n"));
901 if (!whyles && adrof1(STRperiodic, &aliases)) {
902 vp = varval(STRtperiod);
904 aliasrun(1, STRperiodic, NULL);
909 if (t - t_period >= interval * 60) {
911 aliasrun(1, STRperiodic, NULL);
916 cleanup_until(&pintr_disabled);
921 * GrP Greg Parker May 2001
922 * Added job_cmd(), which is run every time a job is started or
923 * foregrounded. The command is passed a single argument, the string
924 * used to start the job originally. With precmd, useful for setting
926 * Cloned from cwd_cmd().
932 cleanup_push(&pintr_disabled, disabled_cleanup);
933 if (jobcmd_active) { /* an error must have been caught */
934 aliasrun(2, STRunalias, STRjobcmd);
935 xprintf("%s", CGETS(22, 14, "Faulty alias 'jobcmd' removed.\n"));
939 if (!whyles && adrof1(STRjobcmd, &aliases)) {
940 struct process *pp = pcurrjob; /* put things back after the hook */
941 aliasrun(2, STRjobcmd, args);
946 cleanup_until(&pintr_disabled);
951 * Karl Kleinpaste, 21oct1983.
952 * Set up a one-word alias command, for use for special things.
953 * This code is based on the mainline of process().
956 aliasrun(int cnt, Char *s1, Char *s2)
958 struct wordent w, *new1, *new2; /* for holding alias name */
959 struct command *t = NULL;
967 seterr = NULL; /* don't repeatedly print err msg. */
970 new1 = xcalloc(1, sizeof w);
971 new1->word = Strsave(s1);
973 /* build a lex list with one word. */
974 w.next = w.prev = new1;
975 new1->next = new1->prev = &w;
978 /* build a lex list with two words. */
979 new2 = xcalloc(1, sizeof w);
980 new2->word = Strsave(s2);
981 w.next = new2->prev = new1;
982 new1->next = w.prev = new2;
983 new1->prev = new2->next = &w;
985 cleanup_push(&w, lex_cleanup);
987 /* Save the old status */
988 status = getn(varval(STRstatus));
990 /* expand aliases like process() does. */
992 /* build a syntax tree for the command. */
993 t = syntax(w.next, &w, 0);
994 cleanup_push(t, syntax_cleanup);
999 cleanup_push(&cnt, psavejob_cleanup); /* cnt is used only as a marker */
1001 /* catch any errors here */
1002 omark = cleanup_push_mark();
1004 /* execute the parse tree. */
1006 * From: Michael Schroeder <mlschroe@immd4.informatik.uni-erlangen.de>
1007 * was execute(t, tpgrp);
1009 execute(t, tpgrp > 0 ? tpgrp : -1, NULL, NULL, TRUE);
1010 /* reset the error catcher to the old place */
1011 cleanup_pop_mark(omark);
1016 * Either precmd, or cwdcmd, or periodic had an error. Call it again so
1017 * that it is removed
1025 * XXX: On the other hand, just interrupting them causes an error too.
1026 * So if we hit ^C in the middle of cwdcmd or periodic the alias gets
1027 * removed. We don't want that. Note that we want to remove precmd
1028 * though, cause that could lead into an infinite loop. This should be
1029 * fixed correctly, but then haderr should give us the whole exit
1030 * status not just true or false.
1032 else if (cwdcmd_active)
1034 else if (beepcmd_active)
1036 else if (periodic_active)
1042 /* Restore status */
1043 setv(STRstatus, putn((tcsh_number_t)status), VAR_READWRITE);
1051 unsigned alrm_time = 0, logout_time, lock_time;
1052 time_t cl, nl, sched_dif;
1054 if ((vp = adrof(STRautologout)) != NULL && vp->vec != NULL) {
1055 if ((cp = vp->vec[0]) != 0) {
1056 if ((logout_time = (unsigned) atoi(short2str(cp)) * 60) > 0) {
1059 * Solaris alarm(2) uses a timer based in clock ticks
1060 * internally so it multiplies our value with CLK_TCK...
1061 * Of course that can overflow leading to unexpected
1062 * results, so we clip it here. Grr. Where is that
1065 if (logout_time >= 0x7fffffff / CLK_TCK)
1066 logout_time = 0x7fffffff / CLK_TCK;
1067 #endif /* SOLARIS2 */
1068 alrm_time = logout_time;
1069 alm_fun = auto_logout;
1072 if ((cp = vp->vec[1]) != 0) {
1073 if ((lock_time = (unsigned) atoi(short2str(cp)) * 60) > 0) {
1075 if (alrm_time == 0 || lock_time < alrm_time) {
1076 alrm_time = lock_time;
1077 alm_fun = auto_lock;
1080 else /* lock_time always < alrm_time */
1082 alrm_time -= lock_time;
1086 if ((nl = sched_next()) != -1) {
1088 sched_dif = nl > cl ? nl - cl : 0;
1089 if ((alrm_time == 0) || ((unsigned) sched_dif < alrm_time)) {
1090 alrm_time = ((unsigned) sched_dif) + 1;
1091 alm_fun = sched_run;
1094 alrmcatch_disabled = 0;
1095 (void) alarm(alrm_time); /* Autologout ON */
1098 #undef RMDEBUG /* For now... */
1101 rmstar(struct wordent *cp)
1103 struct wordent *we, *args;
1104 struct wordent *tmp, *del;
1107 static Char STRrmdebug[] = {'r', 'm', 'd', 'e', 'b', 'u', 'g', '\0'};
1109 #endif /* RMDEBUG */
1112 int ask, doit, star = 0, silent = 0;
1114 if (!adrof(STRrmstar))
1117 tag = varval(STRrmdebug);
1118 #endif /* RMDEBUG */
1120 while (*we->word == ';' && we != cp)
1125 xprintf(CGETS(22, 7, "parsing command line\n"));
1126 #endif /* RMDEBUG */
1127 if (!Strcmp(we->word, STRrm)) {
1129 ask = (*args->word != '-');
1130 while (*args->word == '-' && !silent) { /* check options */
1131 for (charac = (args->word + 1); *charac && !silent; charac++)
1132 silent = (*charac == 'i' || *charac == 'f');
1135 ask = (ask || (!ask && !silent));
1137 for (; !star && *args->word != ';'
1138 && args != cp; args = args->next)
1139 if (!Strcmp(args->word, STRstar))
1142 xprintf("%s", CGETS(22, 8,
1143 "Do you really want to delete all files? [n/y] "));
1145 (void) force_read(SHIN, &c, 1);
1147 * Perhaps we should use the yesexpr from the
1150 doit = (strchr(CGETS(22, 14, "Yy"), c) != NULL);
1151 while (c != '\n' && force_read(SHIN, &c, 1) == 1)
1154 /* remove the command instead */
1157 xprintf(CGETS(22, 9,
1158 "skipping deletion of files!\n"));
1159 #endif /* RMDEBUG */
1161 *tmp->word != '\n' &&
1162 *tmp->word != ';' && tmp != cp;) {
1163 tmp->prev->next = tmp->next;
1164 tmp->next->prev = tmp->prev;
1170 if (*tmp->word == ';') {
1171 tmp->prev->next = tmp->next;
1172 tmp->next->prev = tmp->prev;
1185 *we->word != ';' && we != cp;
1188 if (*we->word == ';')
1193 xprintf(CGETS(22, 10, "command line now is:\n"));
1194 for (we = cp->next; we != cp; we = we->next)
1195 xprintf("%S ", we->word);
1197 #endif /* RMDEBUG */
1202 /* Check if command is in continue list
1203 and do a "aliasing" if it exists as a job in background */
1205 #undef CNDEBUG /* For now */
1207 continue_jobs(struct wordent *cp)
1210 struct process *pp, *np;
1211 Char *cmd, *continue_list, *continue_args_list;
1215 static Char STRcndebug[] =
1216 {'c', 'n', 'd', 'e', 'b', 'u', 'g', '\0'};
1217 #endif /* CNDEBUG */
1218 int in_cont_list, in_cont_arg_list;
1222 tag = varval(STRcndebug);
1223 #endif /* CNDEBUG */
1224 continue_list = varval(STRcontinue);
1225 continue_args_list = varval(STRcontinue_args);
1226 if (*continue_list == '\0' && *continue_args_list == '\0')
1230 while (*we->word == ';' && we != cp)
1235 xprintf(CGETS(22, 11, "parsing command line\n"));
1236 #endif /* CNDEBUG */
1238 in_cont_list = inlist(continue_list, cmd);
1239 in_cont_arg_list = inlist(continue_args_list, cmd);
1240 if (in_cont_list || in_cont_arg_list) {
1243 xprintf(CGETS(22, 12, "in one of the lists\n"));
1244 #endif /* CNDEBUG */
1246 for (pp = proclist.p_next; pp; pp = pp->p_next) {
1247 if (prefix(cmd, pp->p_command)) {
1255 insert(we, in_cont_arg_list);
1259 *we->word != ';' && we != cp;
1262 if (*we->word == ';')
1267 xprintf(CGETS(22, 13, "command line now is:\n"));
1268 for (we = cp->next; we != cp; we = we->next)
1269 xprintf("%S ", we->word);
1271 #endif /* CNDEBUG */
1275 /* The actual "aliasing" of for backgrounds() is done here
1276 with the aid of insert_we(). */
1278 insert(struct wordent *pl, int file_args)
1280 struct wordent *now, *last;
1281 Char *cmd, *bcmd, *cp1, *cp2;
1283 Char *upause = STRunderpause;
1284 size_t p_len = Strlen(upause);
1286 cmd_len = Strlen(pl->word);
1287 cmd = xcalloc(1, (cmd_len + 1) * sizeof(Char));
1288 (void) Strcpy(cmd, pl->word);
1289 /* Do insertions at beginning, first replace command word */
1294 now->word = xcalloc(1, 5 * sizeof(Char));
1295 (void) Strcpy(now->word, STRecho);
1297 now = xcalloc(1, sizeof(struct wordent));
1298 now->word = xcalloc(1, 6 * sizeof(Char));
1299 (void) Strcpy(now->word, STRbackqpwd);
1302 for (last = now; *last->word != '\n' && *last->word != ';';
1306 now = xcalloc(1, sizeof(struct wordent));
1307 now->word = xcalloc(1, 2 * sizeof(Char));
1308 (void) Strcpy(now->word, STRgt);
1309 insert_we(now, last->prev);
1311 now = xcalloc(1, sizeof(struct wordent));
1312 now->word = xcalloc(1, 2 * sizeof(Char));
1313 (void) Strcpy(now->word, STRbang);
1314 insert_we(now, last->prev);
1316 now = xcalloc(1, sizeof(struct wordent));
1317 now->word = xcalloc(1, (cmd_len + p_len + 4) * sizeof(Char));
1323 while ((*cp1++ = *cp2++) != '\0')
1327 while ((*cp1++ = *cp2++) != '\0')
1329 insert_we(now, last->prev);
1331 now = xcalloc(1, sizeof(struct wordent));
1332 now->word = xcalloc(1, 2 * sizeof(Char));
1333 (void) Strcpy(now->word, STRsemi);
1334 insert_we(now, last->prev);
1335 bcmd = xcalloc(1, (cmd_len + 2) * sizeof(Char));
1337 Strcpy(bcmd + 1, cmd);
1338 now = xcalloc(1, sizeof(struct wordent));
1340 insert_we(now, last->prev);
1343 struct wordent *del;
1347 now->word = xcalloc(1, (cmd_len + 2) * sizeof(Char));
1349 Strcpy(now->word + 1, cmd);
1350 for (now = now->next;
1351 *now->word != '\n' && *now->word != ';' && now != pl;) {
1352 now->prev->next = now->next;
1353 now->next->prev = now->prev;
1363 insert_we(struct wordent *new, struct wordent *where)
1367 new->next = where->next;
1369 new->next->prev = new;
1373 inlist(Char *list, Char *name)
1384 if (*n == '\0' && (*l == ' ' || *l == '\0'))
1390 while (*l && *l != ' ')
1391 l++; /* skip to blank */
1392 while (*l && *l == ' ')
1393 l++; /* and find first nonblank character */
1400 #endif /* BSDJOBS */
1404 * Implement a small cache for tilde names. This is used primarily
1405 * to expand tilde names to directories, but also
1406 * we can find users from their home directories for the tilde
1407 * prompt, on machines where yp lookup is slow this can be a big win...
1408 * As with any cache this can run out of sync, rehash can sync it again.
1410 static struct tildecache {
1418 static size_t tsize = TILINCR;
1421 tildecompare(const void *xp1, const void *xp2)
1423 const struct tildecache *p1, *p2;
1427 return Strcmp(p1->user, p2->user);
1431 gethomedir(const Char *us)
1435 char **res, **res1, *cp;
1439 pp = xgetpwnam(short2str(us));
1445 /* Don't return if root */
1446 if (pp->pw_dir[0] == '/' && pp->pw_dir[1] == '\0')
1450 return Strsave(str2short(pp->pw_dir));
1453 res = hes_resolve(short2str(us), "filsys");
1456 if ((*res) != NULL) {
1458 * Look at the first token to determine how to interpret
1460 * Yes, strtok is evil (it's not thread-safe), but it's also
1463 cp = strtok(*res, " ");
1464 if (strcmp(cp, "AFS") == 0) {
1465 /* next token is AFS pathname.. */
1466 cp = strtok(NULL, " ");
1468 rp = Strsave(str2short(cp));
1469 } else if (strcmp(cp, "NFS") == 0) {
1471 if ((strtok(NULL, " ")) && /* skip remote pathname */
1472 (strtok(NULL, " ")) && /* skip host */
1473 (strtok(NULL, " ")) && /* skip mode */
1474 (cp = strtok(NULL, " "))) {
1475 rp = Strsave(str2short(cp));
1479 for (res1 = res; *res1; res1++)
1482 /* Don't return if root */
1483 if (rp != NULL && rp[0] == '/' && rp[1] == '\0') {
1495 gettilde(const Char *us)
1497 struct tildecache *bp1, *bp2, *bp;
1500 /* Ignore NIS special names */
1501 if (*us == '+' || *us == '-')
1505 tcache = xmalloc(TILINCR * sizeof(struct tildecache));
1509 for (bp1 = tcache, bp2 = tcache + tlength; bp1 < bp2;) {
1512 bp = bp1 + ((bp2 - bp1) >> 1);
1513 if ((i = *us - *bp->user) == 0 && (i = Strcmp(us, bp->user)) == 0)
1521 * Not in the cache, try to get it from the passwd file
1523 hd = gethomedir(us);
1530 tcache[tlength].user = Strsave(us);
1531 tcache[tlength].home = hd;
1532 tcache[tlength++].hlen = Strlen(hd);
1534 qsort(tcache, tlength, sizeof(struct tildecache), tildecompare);
1536 if (tlength == tsize) {
1538 tcache = xrealloc(tcache, tsize * sizeof(struct tildecache));
1544 * Return the username if the directory path passed contains a
1545 * user's home directory in the tilde cache, otherwise return NULL
1546 * hm points to the place where the path became different.
1547 * Special case: Our own home directory.
1548 * If we are passed a null pointer, then we flush the cache.
1551 getusername(Char **hm)
1557 for (i = 0; i < tlength; i++) {
1558 xfree(tcache[i].home);
1559 xfree(tcache[i].user);
1568 if (((h = varval(STRhome)) != STRNULL) &&
1569 (Strncmp(p, h, j = Strlen(h)) == 0) &&
1570 (p[j] == '/' || p[j] == '\0')) {
1574 for (i = 0; i < tlength; i++)
1575 if ((Strncmp(p, tcache[i].home, (j = tcache[i].hlen)) == 0) &&
1576 (p[j] == '/' || p[j] == '\0')) {
1578 return tcache[i].user;
1585 * set the shell-level var to 1 or apply change to it.
1592 if ((cp = getenv("SHLVL")) != NULL) {
1600 if (adrof(STRshlvl) != NULL)
1602 Unsetenv(STRKSHLVL);
1607 p = Itoa(val, 0, 0);
1608 cleanup_push(p, xfree);
1609 setv(STRshlvl, p, VAR_READWRITE);
1612 tsetenv(STRKSHLVL, p);
1616 setcopy(STRshlvl, STR1, VAR_READWRITE);
1617 tsetenv(STRKSHLVL, STR1);
1623 * Try to recover from a read error
1626 fixio(int fd, int e)
1629 case -1: /* Make sure that the code is reachable */
1634 #endif /* EWOULDBLOCK */
1636 #if defined(POSIX) && defined(EAGAIN)
1637 # if !defined(EWOULDBLOCK) || EWOULDBLOCK != EAGAIN
1640 # endif /* !EWOULDBLOCK || EWOULDBLOCK != EAGAIN */
1641 #endif /* POSIX && EAGAIN */
1647 * Great! we have on suns 3 flavors and 5 names...
1648 * I hope that will cover everything.
1649 * I added some more defines... many systems have different defines.
1650 * Rather than dealing with getting the right includes, we'll just
1651 * cover all the known possibilities here. -- sterling@netcom.com
1654 # define O_NONBLOCK 0
1655 # endif /* O_NONBLOCK */
1658 # endif /* O_NDELAY */
1664 # endif /* _FNBIO */
1667 # endif /* FNONBIO */
1669 # define FNONBLOCK 0
1670 # endif /* FNONBLOCK */
1672 # define _FNONBLOCK 0
1673 # endif /* _FNONBLOCK */
1676 # endif /* FNDELAY */
1679 # endif /* _FNDELAY */
1680 # ifndef FNDLEAY /* Some linux versions have this typo */
1682 # endif /* FNDLEAY */
1683 if ((e = fcntl(fd, F_GETFL, 0)) == -1)
1686 e &= ~(O_NDELAY|O_NONBLOCK|FNBIO|_FNBIO|FNONBIO|FNONBLOCK|_FNONBLOCK|
1687 FNDELAY|_FNDELAY|FNDLEAY); /* whew! */
1688 if (fcntl(fd, F_SETFL, e) == -1)
1692 # endif /* F_SETFL */
1696 if (ioctl(fd, FIONBIO, (ioctl_t) &e) == -1)
1698 # endif /* FIONBIO */
1700 #endif /* FDRETRY */
1715 collate(const Char *a, const Char *b)
1718 #ifdef SHORT_STRINGS
1719 /* This strips the quote bit as a side effect */
1720 char *sa = strsave(short2str(a));
1721 char *sb = strsave(short2str(b));
1723 char *sa = strip(strsave(a));
1724 char *sb = strip(strsave(b));
1725 #endif /* SHORT_STRINGS */
1727 #if defined(NLS) && defined(HAVE_STRCOLL)
1728 errno = 0; /* strcoll sets errno, another brain-damage */
1730 rv = strcoll(sa, sb);
1733 * We should be checking for errno != 0, but some systems
1734 * forget to reset errno to 0. So we only check for the
1735 * only documented valid errno value for strcoll [EINVAL]
1737 if (errno == EINVAL) {
1740 stderror(ERR_SYSTEM, "strcoll", strerror(errno));
1743 rv = strcmp(sa, sb);
1744 #endif /* NLS && HAVE_STRCOLL */
1754 * From: peter@zeus.dialix.oz.au (Peter Wemm)
1755 * If exec() fails look first for a #! [word] [word] ....
1756 * If it is, splice the header into the argument list and retry.
1758 #define HACKBUFSZ 1024 /* Max chars in #! vector */
1760 hashbang(int fd, Char ***vp)
1762 struct blk_buf sarg = BLK_BUF_INIT;
1763 char lbuf[HACKBUFSZ], *p, *ws;
1765 int fw = 0; /* found at least one word */
1768 #endif /* WINNT_NATIVE */
1770 if (xread(fd, lbuf, HACKBUFSZ) <= 0)
1773 ws = 0; /* word started = 0 */
1775 for (p = lbuf; p < &lbuf[HACKBUFSZ]; ) {
1779 #if defined(WINNT_NATIVE) || defined (__CYGWIN__)
1781 #endif /* WINNT_NATIVE || __CYGWIN__ */
1782 if (ws) { /* a blank after a word.. save it */
1786 real = hb_subst(ws);
1792 #endif /* WINNT_NATIVE */
1793 bb_append(&sarg, SAVE(ws));
1799 case '\0': /* Whoa!! what the hell happened */
1802 case '\n': /* The end of the line. */
1806 #endif /* WINNT_NATIVE */
1807 ws) { /* terminate the last word */
1810 /* deal with the 1-word case */
1812 real = hb_subst(ws);
1816 #endif /* !WINNT_NATIVE */
1818 bb_append(&sarg, SAVE(ws));
1821 *vp = bb_finish(&sarg);
1828 if (!ws) /* Start a new word? */
1838 #endif /* HASHBANG */
1850 getremotehost(int dest_fd)
1852 const char *host = NULL;
1854 struct sockaddr_storage saddr;
1855 static char hbuf[NI_MAXHOST];
1858 struct sockaddr_in saddr;
1860 socklen_t len = sizeof(saddr);
1863 if (getpeername(SHIN, (struct sockaddr *) &saddr, &len) != -1 &&
1864 (saddr.ss_family == AF_INET6 || saddr.ss_family == AF_INET)) {
1865 int flag = NI_NUMERICHOST;
1867 #ifdef NI_WITHSCOPEID
1868 flag |= NI_WITHSCOPEID;
1870 getnameinfo((struct sockaddr *)&saddr, len, hbuf, sizeof(hbuf),
1874 if (getpeername(SHIN, (struct sockaddr *) &saddr, &len) != -1 &&
1875 saddr.sin_family == AF_INET) {
1877 if ((hp = gethostbyaddr((char *)&saddr.sin_addr, sizeof(struct in_addr),
1882 host = inet_ntoa(saddr.sin_addr);
1885 #ifdef HAVE_STRUCT_UTMP_UT_HOST
1888 char *name = utmphost();
1889 /* Avoid empty names and local X displays */
1890 if (name != NULL && *name != '\0' && *name != ':') {
1891 struct in_addr addr;
1894 /* Look for host:display.screen */
1896 * There is conflict with IPv6 address and X DISPLAY. So,
1897 * we assume there is no IPv6 address in utmp and don't
1900 if ((sptr = strchr(name, ':')) != NULL)
1902 /* Leave IPv4 address as is */
1904 * we use inet_addr here, not inet_aton because many systems
1905 * have not caught up yet.
1907 addr.s_addr = inet_addr(name);
1908 if (addr.s_addr != (unsigned int)~0)
1914 char dbuf[MAXHOSTNAMELEN];
1915 struct addrinfo hints, *res = NULL;
1917 memset(&hints, 0, sizeof(hints));
1918 hints.ai_family = PF_UNSPEC;
1919 hints.ai_socktype = SOCK_STREAM;
1920 hints.ai_flags = AI_PASSIVE | AI_CANONNAME;
1921 if (strlen(name) < utmphostsize())
1923 if (getaddrinfo(name, NULL, &hints, &res) != 0)
1925 } else if (gethostname(dbuf, sizeof(dbuf)) == 0 &&
1926 (dbuf[sizeof(dbuf)-1] = '\0', /*FIXME: ugly*/
1927 (domain = strchr(dbuf, '.')) != NULL)) {
1928 for (s = strchr(name, '.');
1929 s != NULL; s = strchr(s + 1, '.')) {
1930 if (*(s + 1) != '\0' &&
1931 (ptr = strstr(domain, s)) != NULL) {
1934 cbuf = strspl(name, ptr + strlen(s));
1935 if (getaddrinfo(cbuf, NULL, &hints, &res) != 0)
1943 if (res->ai_canonname != NULL) {
1944 strncpy(hbuf, res->ai_canonname, sizeof(hbuf));
1945 hbuf[sizeof(hbuf) - 1] = '\0';
1951 if ((hp = gethostbyname(name)) == NULL) {
1952 /* Try again eliminating the trailing domain */
1953 if ((ptr = strchr(name, '.')) != NULL) {
1955 if ((hp = gethostbyname(name)) != NULL)
1972 left = strlen(host);
1976 res = xwrite(dest_fd, host, left);
1987 * From: <lesv@ppvku.ericsson.se> (Lennart Svensson)
1992 struct sigaction sa;
1993 struct strbuf hostname = strbuf_INIT;
1994 int fds[2], wait_options, status;
1995 pid_t pid, wait_res;
1997 sa.sa_handler = SIG_DFL; /* Make sure a zombie is created */
1998 sigemptyset(&sa.sa_mask);
2000 sigaction(SIGCHLD, &sa, NULL);
2006 /* Don't get stuck if the resolver does not work! */
2007 signal(SIGALRM, palarm);
2009 sigaddset(&set, SIGALRM);
2010 (void)sigprocmask(SIG_UNBLOCK, &set, NULL);
2012 getremotehost(fds[1]);
2020 res = xread(fds[0], buf, sizeof(buf));
2023 wait_options = WNOHANG;
2028 strbuf_appendn(&hostname, buf, res);
2032 cleanup_push(&hostname, strbuf_cleanup);
2034 while ((wait_res = waitpid(pid, &status, wait_options)) == -1
2036 handle_pending_signals();
2037 if (hostname.len > 0 && wait_res == pid && WIFEXITED(status)
2038 && WEXITSTATUS(status) == 0) {
2039 strbuf_terminate(&hostname);
2040 tsetenv(STRREMOTEHOST, str2short(hostname.s));
2042 cleanup_until(&hostname);
2045 /* From: casper@fwi.uva.nl (Casper H.S. Dik), for Solaris 2.3 */
2050 #endif /* REMOTEHOST */
2052 #ifndef WINNT_NATIVE
2054 * indicate if a terminal type is defined in terminfo/termcap
2055 * (by default the current term type). This allows ppl to look
2056 * for a working term type automatically in their login scripts
2057 * when using a terminal known as different things on different
2061 dotermname(Char **v, struct command *c)
2065 * Maximum size of a termcap record. We make it twice as large.
2067 char termcap_buffer[2048];
2070 /* try to find which entry we should be looking for */
2071 termtype = (v[1] == NULL ? getenv("TERM") : short2str(v[1]));
2072 if (termtype == NULL) {
2073 /* no luck - the user didn't provide one and none is
2074 * specified in the environment
2076 setcopy(STRstatus, STR1, VAR_READWRITE);
2081 * we use the termcap function - if we are using terminfo we
2082 * will end up with it's compatibility function
2083 * terminfo/termcap will be initialized with the new
2084 * type but we don't care because tcsh has cached all the things
2087 if (tgetent(termcap_buffer, termtype) == 1) {
2088 xprintf("%s\n", termtype);
2089 setcopy(STRstatus, STR0, VAR_READWRITE);
2091 setcopy(STRstatus, STR1, VAR_READWRITE);
2093 #endif /* WINNT_NATIVE */