2 * tc.func.c: New tcsh builtins.
5 * Copyright (c) 1980, 1991 The Regents of the University of California.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 #include "ed.defns.h" /* for the function names */
39 #else /* WINNT_NATIVE */
41 #endif /* WINNT_NATIVE */
45 #include <afs/kautils.h>
46 long ka_UserAuthenticateGeneral();
52 extern time_t t_period;
53 extern int just_signaled;
54 static int precmd_active = 0;
55 static int jobcmd_active = 0; /* GrP */
56 int postcmd_active = 0;
57 static int periodic_active = 0;
58 static int cwdcmd_active = 0; /* PWP: for cwd_cmd */
59 static int beepcmd_active = 0;
60 static void (*alm_fun)(void) = NULL;
62 static void auto_logout (void);
63 static char *xgetpass (const char *);
64 static void auto_lock (void);
66 static void insert (struct wordent *, int);
67 static void insert_we (struct wordent *, struct wordent *);
68 static int inlist (Char *, Char *);
70 static int tildecompare (const void *, const void *);
71 static Char *gethomedir (const Char *);
73 static void palarm (int);
74 static void getremotehost (int);
75 #endif /* REMOTEHOST */
82 * expand_lex: Take the given lex and return an expanded version of it.
83 * First guy in lex list is ignored; last guy is ^J which we ignore.
84 * Only take lex'es from position 'from' to position 'to' inclusive
86 * Note: csh sometimes sets bit 8 in characters which causes all kinds
87 * of problems if we don't mask it here. Note: excl's in lexes have been
88 * un-back-slashed and must be re-back-slashed
91 /* PWP: this is a combination of the old sprlex() and the expand_lex from
92 the magic-space stuff */
95 expand_lex(const struct wordent *sp0, int from, int to)
97 struct Strbuf buf = Strbuf_INIT;
98 const struct wordent *sp;
105 if (!sp0 || (sp = sp0->next) == sp0 || sp == (sp0 = sp0->prev))
106 return Strbuf_finish(&buf); /* null lex */
109 if ((i >= from) && (i <= to)) { /* if in range */
110 for (s = sp->word; *s; s++) {
112 * bugfix by Michael Bloom: anything but the current history
113 * character {(PWP) and backslash} seem to be dealt with
117 && (((*s & TRIM) == HIST && HIST != '\0') ||
118 (((*s & TRIM) == '\'') && (prev_c != '\\')) ||
119 (((*s & TRIM) == '\"') && (prev_c != '\\')))) {
120 Strbuf_append1(&buf, '\\');
122 #if INVALID_BYTE != 0
123 if ((*s & INVALID_BYTE) != INVALID_BYTE) /* *s < INVALID_BYTE */
124 Strbuf_append1(&buf, *s & TRIM);
126 Strbuf_append1(&buf, *s);
128 Strbuf_append1(&buf, *s & TRIM);
132 Strbuf_append1(&buf, ' ');
139 buf.len--; /* get rid of trailing space */
141 return Strbuf_finish(&buf);
145 sprlex(const struct wordent *sp0)
147 return expand_lex(sp0, 0, INT_MAX);
152 Itoa(int n, size_t min_digits, Char attributes)
155 * The array size here is derived from
157 * which is guaranteed to be enough for a decimal
158 * representation. We add 1 because integer divide
164 Char buf[CHAR_BIT * sizeof(int) / 3 + 1], *res, *p, *s;
165 unsigned int un; /* handle most negative # too */
166 int pad = (min_digits != 0);
168 if (sizeof(buf) - 1 < min_digits)
169 min_digits = sizeof(buf) - 1;
177 *p++ = un % 10 + '0';
179 } while ((pad && (ssize_t)--min_digits > 0) || un != 0);
181 res = xmalloc((p - buf + 2) * sizeof(*res));
186 *s++ = *--p | attributes;
195 dolist(Char **v, struct command *c)
203 struct Strbuf word = Strbuf_INIT;
205 Strbuf_terminate(&word);
206 cleanup_push(&word, Strbuf_cleanup);
207 (void) t_search(&word, LIST, TW_ZERO, 0, STRNULL, 0);
208 cleanup_until(&word);
211 v = glob_all_or_error(v);
213 cleanup_push(globbed, blk_cleanup);
214 for (k = 0; v[k] != NULL && v[k][0] != '-'; k++)
218 * We cannot process a flag therefore we let ls do it right.
222 struct wordent cmd, *nextword, *lastword;
228 cleanup_push(&pintr_disabled, disabled_cleanup);
238 /* Look at listflags, to add -A to the flags, to get a path
239 of ls if necessary */
240 if ((vp = adrof(STRlistflags)) != NULL && vp->vec != NULL &&
241 vp->vec[0] != STRNULL) {
242 if (vp->vec[1] != NULL && vp->vec[1][0] != '\0')
244 for (cp = vp->vec[0]; *cp; cp++)
262 nextword = xcalloc(1, sizeof cmd);
263 nextword->word = Strsave(lspath);
264 lastword->next = nextword;
265 nextword->prev = lastword;
267 nextword = xcalloc(1, sizeof cmd);
268 nextword->word = Strsave(STRmCF);
269 lastword->next = nextword;
270 nextword->prev = lastword;
271 #if defined(KANJI) && defined(SHORT_STRINGS) && defined(DSPMBYTE)
274 nextword = xcalloc(1, sizeof cmd);
275 nextword->word = Strsave(STRmmliteral);
276 lastword->next = nextword;
277 nextword->prev = lastword;
281 if (color_context_ls) {
283 nextword = xcalloc(1, sizeof cmd);
284 nextword->word = Strsave(STRmmcolormauto);
285 lastword->next = nextword;
286 nextword->prev = lastword;
288 #endif /* COLOR_LS_F */
290 for (cp = *v; cp; cp = *++v) {
291 nextword = xcalloc(1, sizeof cmd);
292 nextword->word = quote(Strsave(cp));
293 lastword->next = nextword;
294 nextword->prev = lastword;
297 lastword->next = &cmd;
299 cleanup_push(&cmd, lex_cleanup);
301 /* build a syntax tree for the command. */
302 t = syntax(cmd.next, &cmd, 0);
303 cleanup_push(t, syntax_cleanup);
306 /* expand aliases like process() does */
308 /* execute the parse tree. */
309 execute(t, tpgrp > 0 ? tpgrp : -1, NULL, NULL, FALSE);
310 /* done. free the lex list and parse tree. */
313 cleanup_until(&pintr_disabled);
317 struct Strbuf buf = Strbuf_INIT;
319 cleanup_push(&buf, Strbuf_cleanup);
320 for (k = 0, i = 0; v[k] != NULL; k++) {
321 tmp = dnormalize(v[k], symlinks == SYM_IGNORE);
322 cleanup_push(tmp, xfree);
323 dp = Strend(tmp) - 1;
324 if (*dp == '/' && dp != tmp)
329 if (stat(short2str(tmp), &st) == -1) {
336 print_by_column(STRNULL, &v[i], k - i, FALSE);
339 xprintf("%S: %s.\n", tmp, strerror(err));
344 else if (S_ISDIR(st.st_mode)) {
350 print_by_column(STRNULL, &v[i], k - i, FALSE);
352 if (k != 0 && v[1] != NULL)
354 xprintf("%S:\n", tmp);
356 for (cp = tmp; *cp; cp++)
357 Strbuf_append1(&buf, (*cp | QUOTE));
358 Strbuf_terminate(&buf);
359 dp = &buf.s[buf.len - 1];
362 (*dp != (Char) (':' | QUOTE)) &&
363 #endif /* WINNT_NATIVE */
364 (*dp != (Char) ('/' | QUOTE))) {
365 Strbuf_append1(&buf, '/');
366 Strbuf_terminate(&buf);
369 (void) t_search(&buf, LIST, TW_ZERO, 0, STRNULL, 0);
378 print_by_column(STRNULL, &v[i], k - i, FALSE);
381 stderror(ERR_SILENT);
384 cleanup_until(globbed);
387 extern int GotTermCaps;
391 dotelltc(Char **v, struct command *c)
402 doechotc(Char **v, struct command *c)
412 dosettc(Char **v, struct command *c)
420 tv[0] = strsave(short2str(v[1]));
421 cleanup_push(tv[0], xfree);
422 tv[1] = strsave(short2str(v[2]));
423 cleanup_push(tv[1], xfree);
425 cleanup_until(tv[0]);
428 /* The dowhich() is by:
429 * Andreas Luik <luik@isaak.isa.de>
430 * I S A GmbH - Informationssysteme fuer computerintegrierte Automatisierung
437 cmd_expand(Char *cmd, Char **str)
439 struct wordent lexp[3];
443 lexp[0].next = &lexp[1];
444 lexp[1].next = &lexp[2];
445 lexp[2].next = &lexp[0];
447 lexp[0].prev = &lexp[2];
448 lexp[1].prev = &lexp[0];
449 lexp[2].prev = &lexp[1];
451 lexp[0].word = STRNULL;
452 lexp[2].word = STRret;
454 if ((vp = adrof1(cmd, &aliases)) != NULL && vp->vec != NULL) {
456 xprintf(CGETS(22, 1, "%S: \t aliased to "), cmd);
461 *str = blkexpand(vp->vec);
465 rv = tellmewhat(lexp, str);
473 dowhich(Char **v, struct command *c)
479 * We don't want to glob dowhich args because we lose quoteing
480 * E.g. which \ls if ls is aliased will not work correctly if
485 rv &= cmd_expand(*v, NULL);
488 setcopy(STRstatus, STR1, VAR_READWRITE);
492 findvv(Char **vv, const char *cp)
494 for (; vv && *vv; vv++) {
496 for (i = 0; (*vv)[i] && (*vv)[i] == cp[i]; i++)
498 if ((*vv)[i] == '\0' && cp[i] == '\0')
504 /* PWP: a hack to start up your stopped editor on a single keystroke */
505 /* jbs - fixed hack so it worked :-) 3/28/89 */
510 struct process *pp, *retp;
511 const char *ep = NULL, *vp = NULL;
513 size_t epl = 0, vpl = 0;
518 if (pcurrent == NULL) /* see if we have any jobs */
519 return NULL; /* nope */
521 if ((varp = adrof(STReditors)) != NULL)
527 if ((ep = getenv("EDITOR")) != NULL) { /* if we have a value */
528 if ((p = strrchr(ep, '/')) != NULL) /* if it has a path */
529 ep = p + 1; /* then we want only the last part */
534 if ((vp = getenv("VISUAL")) != NULL) { /* if we have a value */
535 if ((p = strrchr(vp, '/')) != NULL) /* and it has a path */
536 vp = p + 1; /* then we want only the last part */
541 for (vpl = 0; vp[vpl] && !isspace((unsigned char)vp[vpl]); vpl++)
543 for (epl = 0; ep[epl] && !isspace((unsigned char)ep[epl]); epl++)
548 for (pp = proclist.p_next; pp; pp = pp->p_next)
549 if (pp->p_procid == pp->p_jobid) {
552 * Only foreground an edit session if it is suspended. Some GUI
553 * editors have may be happily running in a separate window, no
554 * point in foregrounding these if they're already running - webb
556 pstatus = (int) (pp->p_flags & PALLSTATES);
557 if (pstatus != PINTERRUPTED && pstatus != PSTOPPED &&
558 pstatus != PSIGNALED)
561 p = short2str(pp->p_command);
562 /* get the first word */
563 for (cp = p; *cp && !isspace((unsigned char) *cp); cp++)
567 if ((cp = strrchr(p, '/')) != NULL) /* and it has a path */
568 cp = cp + 1; /* then we want only the last part */
570 cp = p; /* else we get all of it */
573 * If we find the current name in the $editors array (if set)
574 * or as $EDITOR or $VISUAL (if $editors not set), fg it.
576 if ((vv && findvv(vv, cp)) ||
577 (epl && strncmp(ep, cp, epl) == 0 && cp[epl] == '\0') ||
578 (vpl && strncmp(vp, cp, vpl) == 0 && cp[vpl] == '\0')) {
580 * If there is a choice, then choose the current process if
581 * available, or the previous process otherwise, or else
582 * anything will do - Robert Webb (robertw@mulga.cs.mu.oz.au).
586 else if (retp == NULL || pp == pprevious)
591 return retp; /* Will be NULL if we didn't find a job */
595 fg_proc_entry(struct process *pp)
605 oGettingInput = GettingInput;
608 ohaderr = haderr; /* we need to ignore setting of haderr due to
609 * process getting stopped by a signal */
610 omark = cleanup_push_mark();
611 if (setexit() == 0) { /* come back here after pjwait */
613 (void) alarm(0); /* No autologout */
614 alrmcatch_disabled = 1;
615 if (!pstart(pp, 1)) {
617 stderror(ERR_BADJOB, pp->p_command, strerror(errno));
621 setalarm(1); /* Autologout back on */
622 cleanup_pop_mark(omark);
625 GettingInput = oGettingInput;
627 disabled_cleanup(&pintr_disabled);
631 xgetpass(const char *prm)
633 static struct strbuf pass; /* = strbuf_INIT; */
636 struct sigaction sa, osa;
638 sa.sa_handler = SIG_IGN;
639 sigemptyset(&sa.sa_mask);
641 (void)sigaction(SIGINT, &sa, &osa);
644 sigaddset(&set, SIGINT);
645 (void)sigprocmask(SIG_UNBLOCK, &set, &oset);
647 cleanup_push(&osa, sigint_cleanup);
648 cleanup_push(&oset, sigprocmask_cleanup);
649 (void) Rawmode(); /* Make sure, cause we want echo off */
650 fd = xopen("/dev/tty", O_RDWR|O_LARGEFILE);
654 cleanup_push(&fd, open_cleanup);
656 xprintf("%s", prm); flush();
661 if (xread(fd, &c, 1) < 1 || c == '\n')
663 strbuf_append1(&pass, c);
665 strbuf_terminate(&pass);
674 extern char *crypt ();
682 * Ask the user for his login password to continue working
683 * On systems that have a shadow password, this will only
684 * work for root, but what can we do?
686 * If we fail to get the password, then we log the user out
701 #if defined(HAVE_AUTH_H) && defined(HAVE_GETAUTHUID)
703 struct authorization *apw;
704 extern char *crypt16 (const char *, const char *);
706 # define XCRYPT(pw, a, b) crypt16(a, b)
708 if ((pw = xgetpwuid(euid)) != NULL && /* effective user passwd */
709 (apw = getauthuid(euid)) != NULL) /* enhanced ultrix passwd */
710 srpp = apw->a_password;
712 #elif defined(HAVE_SHADOW_H)
716 # define XCRYPT(pw, a, b) crypt(a, b)
718 if ((pw = xgetpwuid(euid)) != NULL) { /* effective user passwd */
720 while ((spw = getspnam(pw->pw_name)) == NULL && errno == EINTR) {
721 handle_pending_signals();
724 if (spw != NULL) /* shadowed passwd */
732 # define XCRYPT(pw, a, b) cygwin_xcrypt(pw, a, b)
734 # define XCRYPT(pw, a, b) crypt(a, b)
737 #if !defined(__MVS__)
738 if ((pw = xgetpwuid(euid)) != NULL) /* effective user passwd */
739 srpp = pw->pw_passwd;
750 setalarm(0); /* Not for locking any more */
752 for (i = 0; i < 5; i++) {
759 if ((safs = varval(STRafsuser)) != STRNULL)
760 afsname = short2str(safs);
762 if ((afsname = getenv("AFSUSER")) == NULL)
763 afsname = pw->pw_name;
765 pp = xgetpass("Password:");
767 crpp = XCRYPT(pw, pp, srpp);
768 if ((crpp && strcmp(crpp, srpp) == 0)
770 || (ka_UserAuthenticateGeneral(KA_USERAUTH_VERSION,
781 (void) memset(pp, 0, strlen(pp));
782 if (GettingInput && !just_signaled) {
791 xprintf(CGETS(22, 2, "\nIncorrect passwd for %s\n"), pw->pw_name);
793 #endif /* NO_CRYPT */
801 xprintf("auto-logout\n");
802 /* Don't leave the tty in raw mode */
806 setcopy(STRlogout, STRautomatic, VAR_READWRITE);
811 GettingInput = FALSE; /* make flush() work to write hist files. Huber*/
823 * Karl Kleinpaste, 21oct1983.
824 * Added precmd(), which checks for the alias
825 * precmd in aliases. If it's there, the alias
826 * is executed as a command. This is done
827 * after mailchk() and just before print-
828 * ing the prompt. Useful for things like printing
829 * one's current directory just before each command.
835 cleanup_push(&pintr_disabled, disabled_cleanup);
836 if (precmd_active) { /* an error must have been caught */
837 aliasrun(2, STRunalias, STRprecmd);
838 xprintf("%s", CGETS(22, 3, "Faulty alias 'precmd' removed.\n"));
842 if (!whyles && adrof1(STRprecmd, &aliases))
843 aliasrun(1, STRprecmd, NULL);
846 cleanup_until(&pintr_disabled);
853 cleanup_push(&pintr_disabled, disabled_cleanup);
854 if (postcmd_active) { /* an error must have been caught */
855 aliasrun(2, STRunalias, STRpostcmd);
856 xprintf("%s", CGETS(22, 3, "Faulty alias 'postcmd' removed.\n"));
860 if (!whyles && adrof1(STRpostcmd, &aliases))
861 aliasrun(1, STRpostcmd, NULL);
864 cleanup_until(&pintr_disabled);
868 * Paul Placeway 11/24/87 Added cwd_cmd by hacking precmd() into
869 * submission... Run every time $cwd is set (after it is set). Useful
870 * for putting your machine and cwd (or anything else) in an xterm title
877 cleanup_push(&pintr_disabled, disabled_cleanup);
878 if (cwdcmd_active) { /* an error must have been caught */
879 aliasrun(2, STRunalias, STRcwdcmd);
880 xprintf("%s", CGETS(22, 4, "Faulty alias 'cwdcmd' removed.\n"));
884 if (!whyles && adrof1(STRcwdcmd, &aliases))
885 aliasrun(1, STRcwdcmd, NULL);
888 cleanup_until(&pintr_disabled);
892 * Joachim Hoenig 07/16/91 Added beep_cmd, run every time tcsh wishes
893 * to beep the terminal bell. Useful for playing nice sounds instead.
899 cleanup_push(&pintr_disabled, disabled_cleanup);
900 if (beepcmd_active) { /* an error must have been caught */
901 aliasrun(2, STRunalias, STRbeepcmd);
902 xprintf("%s", CGETS(22, 5, "Faulty alias 'beepcmd' removed.\n"));
906 if (!whyles && adrof1(STRbeepcmd, &aliases))
907 aliasrun(1, STRbeepcmd, NULL);
910 cleanup_until(&pintr_disabled);
915 * Karl Kleinpaste, 18 Jan 1984.
916 * Added period_cmd(), which executes the alias "periodic" every
917 * $tperiod minutes. Useful for occasional checking of msgs and such.
928 cleanup_push(&pintr_disabled, disabled_cleanup);
929 if (periodic_active) { /* an error must have been caught */
930 aliasrun(2, STRunalias, STRperiodic);
931 xprintf("%s", CGETS(22, 6, "Faulty alias 'periodic' removed.\n"));
935 if (!whyles && adrof1(STRperiodic, &aliases)) {
936 vp = varval(STRtperiod);
938 aliasrun(1, STRperiodic, NULL);
943 if (t - t_period >= interval * 60) {
945 aliasrun(1, STRperiodic, NULL);
950 cleanup_until(&pintr_disabled);
955 * GrP Greg Parker May 2001
956 * Added job_cmd(), which is run every time a job is started or
957 * foregrounded. The command is passed a single argument, the string
958 * used to start the job originally. With precmd, useful for setting
960 * Cloned from cwd_cmd().
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"));
975 if (!whyles && adrof1(STRjobcmd, &aliases)) {
976 struct process *pp = pcurrjob; /* put things back after the hook */
977 aliasrun(2, STRjobcmd, args);
982 cleanup_until(&pintr_disabled);
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().
992 aliasrun(int cnt, Char *s1, Char *s2)
994 struct wordent w, *new1, *new2; /* for holding alias name */
995 struct command *t = NULL;
1003 seterr = NULL; /* don't repeatedly print err msg. */
1006 new1 = xcalloc(1, sizeof w);
1007 new1->word = Strsave(s1);
1009 /* build a lex list with one word. */
1010 w.next = w.prev = new1;
1011 new1->next = new1->prev = &w;
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;
1021 cleanup_push(&w, lex_cleanup);
1023 /* Save the old status */
1024 status = getn(varval(STRstatus));
1026 /* expand aliases like process() does. */
1028 /* build a syntax tree for the command. */
1029 t = syntax(w.next, &w, 0);
1030 cleanup_push(t, syntax_cleanup);
1035 cleanup_push(&cnt, psavejob_cleanup); /* cnt is used only as a marker */
1037 /* catch any errors here */
1038 omark = cleanup_push_mark();
1040 /* execute the parse tree. */
1042 * From: Michael Schroeder <mlschroe@immd4.informatik.uni-erlangen.de>
1043 * was execute(t, tpgrp);
1045 execute(t, tpgrp > 0 ? tpgrp : -1, NULL, NULL, TRUE);
1046 /* reset the error catcher to the old place */
1047 cleanup_pop_mark(omark);
1052 * Either precmd, or cwdcmd, or periodic had an error. Call it again so
1053 * that it is removed
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.
1068 else if (cwdcmd_active)
1070 else if (beepcmd_active)
1072 else if (periodic_active)
1078 /* Restore status */
1079 setv(STRstatus, putn((tcsh_number_t)status), VAR_READWRITE);
1087 unsigned alrm_time = 0, logout_time, lock_time;
1088 time_t cl, nl, sched_dif;
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) {
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
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;
1108 if ((cp = vp->vec[1]) != 0) {
1109 if ((lock_time = (unsigned) atoi(short2str(cp)) * 60) > 0) {
1111 if (alrm_time == 0 || lock_time < alrm_time) {
1112 alrm_time = lock_time;
1113 alm_fun = auto_lock;
1116 else /* lock_time always < alrm_time */
1118 alrm_time -= lock_time;
1122 if ((nl = sched_next()) != -1) {
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;
1130 alrmcatch_disabled = 0;
1131 (void) alarm(alrm_time); /* Autologout ON */
1134 #undef RMDEBUG /* For now... */
1137 rmstar(struct wordent *cp)
1139 struct wordent *we, *args;
1140 struct wordent *tmp, *del;
1143 static Char STRrmdebug[] = {'r', 'm', 'd', 'e', 'b', 'u', 'g', '\0'};
1145 #endif /* RMDEBUG */
1147 int ask, doit, star = 0, silent = 0, opintr_disabled;
1149 if (!adrof(STRrmstar))
1152 tag = varval(STRrmdebug);
1153 #endif /* RMDEBUG */
1155 while (*we->word == ';' && we != cp)
1157 opintr_disabled = pintr_disabled;
1160 Char *cmd = we->word;
1161 if (cmd[0] == STRQNULL[0])
1165 xprintf(CGETS(22, 7, "parsing command line [%S]\n"), cmd);
1166 #endif /* RMDEBUG */
1167 if (!StrQcmp(cmd, STRrm)) {
1169 ask = (*args->word != '-');
1170 while (*args->word == '-' && !silent) { /* check options */
1171 for (charac = (args->word + 1); *charac && !silent; charac++)
1172 silent = (*charac == 'i' || *charac == 'f');
1175 ask = (ask || (!ask && !silent));
1177 for (; !star && *args->word != ';'
1178 && args != cp; args = args->next)
1179 if (!Strcmp(args->word, STRstar))
1182 doit = getYN(CGETS(22, 8,
1183 "Do you really want to delete all files? [N/y] "));
1185 /* remove the command instead */
1188 xprintf(CGETS(22, 9,
1189 "skipping deletion of files!\n"));
1190 #endif /* RMDEBUG */
1192 *tmp->word != '\n' &&
1193 *tmp->word != ';' && tmp != cp;) {
1194 tmp->prev->next = tmp->next;
1195 tmp->next->prev = tmp->prev;
1201 if (*tmp->word == ';') {
1202 tmp->prev->next = tmp->next;
1203 tmp->next->prev = tmp->prev;
1216 *we->word != ';' && we != cp;
1219 if (*we->word == ';')
1224 xprintf(CGETS(22, 10, "command line now is:\n"));
1225 for (we = cp->next; we != cp; we = we->next)
1226 xprintf("[%S] ", we->word);
1228 #endif /* RMDEBUG */
1229 pintr_disabled = opintr_disabled;
1234 /* Check if command is in continue list
1235 and do a "aliasing" if it exists as a job in background */
1237 #undef CNDEBUG /* For now */
1239 continue_jobs(struct wordent *cp)
1242 struct process *pp, *np;
1243 Char *cmd, *continue_list, *continue_args_list;
1247 static Char STRcndebug[] =
1248 {'c', 'n', 'd', 'e', 'b', 'u', 'g', '\0'};
1249 #endif /* CNDEBUG */
1250 int in_cont_list, in_cont_arg_list;
1254 tag = varval(STRcndebug);
1255 #endif /* CNDEBUG */
1256 continue_list = varval(STRcontinue);
1257 continue_args_list = varval(STRcontinue_args);
1258 if (*continue_list == '\0' && *continue_args_list == '\0')
1262 while (*we->word == ';' && we != cp)
1267 xprintf(CGETS(22, 11, "parsing command line\n"));
1268 #endif /* CNDEBUG */
1270 in_cont_list = inlist(continue_list, cmd);
1271 in_cont_arg_list = inlist(continue_args_list, cmd);
1272 if (in_cont_list || in_cont_arg_list) {
1275 xprintf(CGETS(22, 12, "in one of the lists\n"));
1276 #endif /* CNDEBUG */
1278 for (pp = proclist.p_next; pp; pp = pp->p_next) {
1279 if (prefix(cmd, pp->p_command)) {
1287 insert(we, in_cont_arg_list);
1291 *we->word != ';' && we != cp;
1294 if (*we->word == ';')
1299 xprintf(CGETS(22, 13, "command line now is:\n"));
1300 for (we = cp->next; we != cp; we = we->next)
1301 xprintf("%S ", we->word);
1303 #endif /* CNDEBUG */
1307 /* The actual "aliasing" of for backgrounds() is done here
1308 with the aid of insert_we(). */
1310 insert(struct wordent *pl, int file_args)
1312 struct wordent *now, *last;
1313 Char *cmd, *bcmd, *cp1, *cp2;
1315 Char *upause = STRunderpause;
1316 size_t p_len = Strlen(upause);
1318 cmd_len = Strlen(pl->word);
1319 cmd = xcalloc(1, (cmd_len + 1) * sizeof(Char));
1320 (void) Strcpy(cmd, pl->word);
1321 /* Do insertions at beginning, first replace command word */
1326 now->word = xcalloc(1, 5 * sizeof(Char));
1327 (void) Strcpy(now->word, STRecho);
1329 now = xcalloc(1, sizeof(struct wordent));
1330 now->word = xcalloc(1, 6 * sizeof(Char));
1331 (void) Strcpy(now->word, STRbackqpwd);
1334 for (last = now; *last->word != '\n' && *last->word != ';';
1338 now = xcalloc(1, sizeof(struct wordent));
1339 now->word = xcalloc(1, 2 * sizeof(Char));
1340 (void) Strcpy(now->word, STRgt);
1341 insert_we(now, last->prev);
1343 now = xcalloc(1, sizeof(struct wordent));
1344 now->word = xcalloc(1, 2 * sizeof(Char));
1345 (void) Strcpy(now->word, STRbang);
1346 insert_we(now, last->prev);
1348 now = xcalloc(1, sizeof(struct wordent));
1349 now->word = xcalloc(1, (cmd_len + p_len + 4) * sizeof(Char));
1355 while ((*cp1++ = *cp2++) != '\0')
1359 while ((*cp1++ = *cp2++) != '\0')
1361 insert_we(now, last->prev);
1363 now = xcalloc(1, sizeof(struct wordent));
1364 now->word = xcalloc(1, 2 * sizeof(Char));
1365 (void) Strcpy(now->word, STRsemi);
1366 insert_we(now, last->prev);
1367 bcmd = xcalloc(1, (cmd_len + 2) * sizeof(Char));
1369 Strcpy(bcmd + 1, cmd);
1370 now = xcalloc(1, sizeof(struct wordent));
1372 insert_we(now, last->prev);
1375 struct wordent *del;
1379 now->word = xcalloc(1, (cmd_len + 2) * sizeof(Char));
1381 Strcpy(now->word + 1, cmd);
1382 for (now = now->next;
1383 *now->word != '\n' && *now->word != ';' && now != pl;) {
1384 now->prev->next = now->next;
1385 now->next->prev = now->prev;
1395 insert_we(struct wordent *new, struct wordent *where)
1399 new->next = where->next;
1401 new->next->prev = new;
1405 inlist(Char *list, Char *name)
1416 if (*n == '\0' && (*l == ' ' || *l == '\0'))
1422 while (*l && *l != ' ')
1423 l++; /* skip to blank */
1424 while (*l && *l == ' ')
1425 l++; /* and find first nonblank character */
1432 #endif /* BSDJOBS */
1436 * Implement a small cache for tilde names. This is used primarily
1437 * to expand tilde names to directories, but also
1438 * we can find users from their home directories for the tilde
1439 * prompt, on machines where yp lookup is slow this can be a big win...
1440 * As with any cache this can run out of sync, rehash can sync it again.
1442 static struct tildecache {
1450 static size_t tsize = TILINCR;
1453 tildecompare(const void *xp1, const void *xp2)
1455 const struct tildecache *p1, *p2;
1459 return Strcmp(p1->user, p2->user);
1463 gethomedir(const Char *us)
1467 char **res, **res1, *cp;
1471 pp = xgetpwnam(short2str(us));
1477 /* Don't return if root */
1478 if (pp->pw_dir[0] == '/' && pp->pw_dir[1] == '\0')
1482 return Strsave(str2short(pp->pw_dir));
1485 res = hes_resolve(short2str(us), "filsys");
1488 if ((*res) != NULL) {
1490 * Look at the first token to determine how to interpret
1492 * Yes, strtok is evil (it's not thread-safe), but it's also
1495 cp = strtok(*res, " ");
1496 if (strcmp(cp, "AFS") == 0) {
1497 /* next token is AFS pathname.. */
1498 cp = strtok(NULL, " ");
1500 rp = Strsave(str2short(cp));
1501 } else if (strcmp(cp, "NFS") == 0) {
1503 if ((strtok(NULL, " ")) && /* skip remote pathname */
1504 (strtok(NULL, " ")) && /* skip host */
1505 (strtok(NULL, " ")) && /* skip mode */
1506 (cp = strtok(NULL, " "))) {
1507 rp = Strsave(str2short(cp));
1511 for (res1 = res; *res1; res1++)
1514 /* Don't return if root */
1515 if (rp != NULL && rp[0] == '/' && rp[1] == '\0') {
1527 gettilde(const Char *us)
1529 struct tildecache *bp1, *bp2, *bp;
1532 /* Ignore NIS special names */
1533 if (*us == '+' || *us == '-')
1537 tcache = xmalloc(TILINCR * sizeof(struct tildecache));
1541 for (bp1 = tcache, bp2 = tcache + tlength; bp1 < bp2;) {
1544 bp = bp1 + ((bp2 - bp1) >> 1);
1545 if ((i = *us - *bp->user) == 0 && (i = Strcmp(us, bp->user)) == 0)
1553 * Not in the cache, try to get it from the passwd file
1555 hd = gethomedir(us);
1562 tcache[tlength].user = Strsave(us);
1563 tcache[tlength].home = hd;
1564 tcache[tlength++].hlen = Strlen(hd);
1566 qsort(tcache, tlength, sizeof(struct tildecache), tildecompare);
1568 if (tlength == tsize) {
1570 tcache = xrealloc(tcache, tsize * sizeof(struct tildecache));
1576 * Return the username if the directory path passed contains a
1577 * user's home directory in the tilde cache, otherwise return NULL
1578 * hm points to the place where the path became different.
1579 * Special case: Our own home directory.
1580 * If we are passed a null pointer, then we flush the cache.
1583 getusername(Char **hm)
1589 for (i = 0; i < tlength; i++) {
1590 xfree(tcache[i].home);
1591 xfree(tcache[i].user);
1600 if (((h = varval(STRhome)) != STRNULL) &&
1601 (Strncmp(p, h, j = Strlen(h)) == 0) &&
1602 (p[j] == '/' || p[j] == '\0')) {
1606 for (i = 0; i < tlength; i++)
1607 if ((Strncmp(p, tcache[i].home, (j = tcache[i].hlen)) == 0) &&
1608 (p[j] == '/' || p[j] == '\0')) {
1610 return tcache[i].user;
1617 * set the shell-level var to 1 or apply change to it.
1624 if ((cp = getenv("SHLVL")) != NULL) {
1632 if (adrof(STRshlvl) != NULL)
1634 Unsetenv(STRKSHLVL);
1639 p = Itoa(val, 0, 0);
1640 cleanup_push(p, xfree);
1641 setv(STRshlvl, p, VAR_READWRITE);
1644 tsetenv(STRKSHLVL, p);
1648 setcopy(STRshlvl, STR1, VAR_READWRITE);
1649 tsetenv(STRKSHLVL, STR1);
1655 * Try to recover from a read error
1658 fixio(int fd, int e)
1661 case -1: /* Make sure that the code is reachable */
1666 #endif /* EWOULDBLOCK */
1668 #if defined(POSIX) && defined(EAGAIN)
1669 # if !defined(EWOULDBLOCK) || EWOULDBLOCK != EAGAIN
1672 # endif /* !EWOULDBLOCK || EWOULDBLOCK != EAGAIN */
1673 #endif /* POSIX && EAGAIN */
1679 * Great! we have on suns 3 flavors and 5 names...
1680 * I hope that will cover everything.
1681 * I added some more defines... many systems have different defines.
1682 * Rather than dealing with getting the right includes, we'll just
1683 * cover all the known possibilities here. -- sterling@netcom.com
1686 # define O_NONBLOCK 0
1687 # endif /* O_NONBLOCK */
1690 # endif /* O_NDELAY */
1696 # endif /* _FNBIO */
1699 # endif /* FNONBIO */
1701 # define FNONBLOCK 0
1702 # endif /* FNONBLOCK */
1704 # define _FNONBLOCK 0
1705 # endif /* _FNONBLOCK */
1708 # endif /* FNDELAY */
1711 # endif /* _FNDELAY */
1712 # ifndef FNDLEAY /* Some linux versions have this typo */
1714 # endif /* FNDLEAY */
1715 if ((e = fcntl(fd, F_GETFL, 0)) == -1)
1718 e &= ~(O_NDELAY|O_NONBLOCK|FNBIO|_FNBIO|FNONBIO|FNONBLOCK|_FNONBLOCK|
1719 FNDELAY|_FNDELAY|FNDLEAY); /* whew! */
1720 if (fcntl(fd, F_SETFL, e) == -1)
1724 # endif /* F_SETFL */
1728 if (ioctl(fd, FIONBIO, (ioctl_t) &e) == -1)
1730 # endif /* FIONBIO */
1732 #endif /* FDRETRY */
1747 collate(const Char *a, const Char *b)
1750 #ifdef SHORT_STRINGS
1751 /* This strips the quote bit as a side effect */
1752 char *sa = strsave(short2str(a));
1753 char *sb = strsave(short2str(b));
1755 char *sa = strip(strsave(a));
1756 char *sb = strip(strsave(b));
1757 #endif /* SHORT_STRINGS */
1759 #if defined(NLS) && defined(HAVE_STRCOLL)
1760 errno = 0; /* strcoll sets errno, another brain-damage */
1762 rv = strcoll(sa, sb);
1765 * We should be checking for errno != 0, but some systems
1766 * forget to reset errno to 0. So we only check for the
1767 * only documented valid errno value for strcoll [EINVAL]
1769 if (errno == EINVAL) {
1772 stderror(ERR_SYSTEM, "strcoll", strerror(errno));
1775 rv = strcmp(sa, sb);
1776 #endif /* NLS && HAVE_STRCOLL */
1786 * From: peter@zeus.dialix.oz.au (Peter Wemm)
1787 * If exec() fails look first for a #! [word] [word] ....
1788 * If it is, splice the header into the argument list and retry.
1790 #define HACKBUFSZ 1024 /* Max chars in #! vector */
1792 hashbang(int fd, Char ***vp)
1794 struct blk_buf sarg = BLK_BUF_INIT;
1795 char lbuf[HACKBUFSZ], *p, *ws;
1797 int fw = 0; /* found at least one word */
1800 #endif /* WINNT_NATIVE */
1802 if (xread(fd, lbuf, HACKBUFSZ) <= 0)
1805 ws = 0; /* word started = 0 */
1807 for (p = lbuf; p < &lbuf[HACKBUFSZ]; ) {
1811 #if defined(WINNT_NATIVE) || defined (__CYGWIN__)
1813 #endif /* WINNT_NATIVE || __CYGWIN__ */
1814 if (ws) { /* a blank after a word.. save it */
1818 real = hb_subst(ws);
1824 #endif /* WINNT_NATIVE */
1825 bb_append(&sarg, SAVE(ws));
1831 case '\0': /* Whoa!! what the hell happened */
1834 case '\n': /* The end of the line. */
1838 #endif /* WINNT_NATIVE */
1839 ws) { /* terminate the last word */
1842 /* deal with the 1-word case */
1844 real = hb_subst(ws);
1848 #endif /* !WINNT_NATIVE */
1850 bb_append(&sarg, SAVE(ws));
1853 *vp = bb_finish(&sarg);
1860 if (!ws) /* Start a new word? */
1870 #endif /* HASHBANG */
1882 getremotehost(int dest_fd)
1884 const char *host = NULL;
1886 struct sockaddr_storage saddr;
1887 static char hbuf[NI_MAXHOST];
1890 struct sockaddr_in saddr;
1892 socklen_t len = sizeof(saddr);
1895 if (getpeername(SHIN, (struct sockaddr *) &saddr, &len) != -1 &&
1896 (saddr.ss_family == AF_INET6 || saddr.ss_family == AF_INET)) {
1897 int flag = NI_NUMERICHOST;
1899 #ifdef NI_WITHSCOPEID
1900 flag |= NI_WITHSCOPEID;
1902 getnameinfo((struct sockaddr *)&saddr, len, hbuf, sizeof(hbuf),
1906 if (getpeername(SHIN, (struct sockaddr *) &saddr, &len) != -1 &&
1907 saddr.sin_family == AF_INET) {
1909 if ((hp = gethostbyaddr((char *)&saddr.sin_addr, sizeof(struct in_addr),
1914 host = inet_ntoa(saddr.sin_addr);
1917 #ifdef HAVE_STRUCT_UTMP_UT_HOST
1920 char *name = utmphost();
1921 /* Avoid empty names and local X displays */
1922 if (name != NULL && *name != '\0' && *name != ':') {
1923 struct in_addr addr;
1926 /* Look for host:display.screen */
1928 * There is conflict with IPv6 address and X DISPLAY. So,
1929 * we assume there is no IPv6 address in utmp and don't
1932 if ((sptr = strchr(name, ':')) != NULL)
1934 /* Leave IPv4 address as is */
1936 * we use inet_addr here, not inet_aton because many systems
1937 * have not caught up yet.
1939 addr.s_addr = inet_addr(name);
1940 if (addr.s_addr != (unsigned int)~0)
1946 char dbuf[MAXHOSTNAMELEN];
1947 struct addrinfo hints, *res = NULL;
1949 memset(&hints, 0, sizeof(hints));
1950 hints.ai_family = PF_UNSPEC;
1951 hints.ai_socktype = SOCK_STREAM;
1952 hints.ai_flags = AI_PASSIVE | AI_CANONNAME;
1953 if (strlen(name) < utmphostsize())
1955 if (getaddrinfo(name, NULL, &hints, &res) != 0)
1957 } else if (gethostname(dbuf, sizeof(dbuf)) == 0 &&
1958 (dbuf[sizeof(dbuf)-1] = '\0', /*FIXME: ugly*/
1959 (domain = strchr(dbuf, '.')) != NULL)) {
1960 for (s = strchr(name, '.');
1961 s != NULL; s = strchr(s + 1, '.')) {
1962 if (*(s + 1) != '\0' &&
1963 (ptr = strstr(domain, s)) != NULL) {
1966 cbuf = strspl(name, ptr + strlen(s));
1967 if (getaddrinfo(cbuf, NULL, &hints, &res) != 0)
1975 if (res->ai_canonname != NULL) {
1976 strncpy(hbuf, res->ai_canonname, sizeof(hbuf));
1977 hbuf[sizeof(hbuf) - 1] = '\0';
1983 if ((hp = gethostbyname(name)) == NULL) {
1984 /* Try again eliminating the trailing domain */
1985 if ((ptr = strchr(name, '.')) != NULL) {
1987 if ((hp = gethostbyname(name)) != NULL)
2004 left = strlen(host);
2008 res = xwrite(dest_fd, host, left);
2019 * From: <lesv@ppvku.ericsson.se> (Lennart Svensson)
2024 struct sigaction sa;
2025 struct strbuf hostname = strbuf_INIT;
2026 int fds[2], wait_options, status;
2027 pid_t pid, wait_res;
2029 sa.sa_handler = SIG_DFL; /* Make sure a zombie is created */
2030 sigemptyset(&sa.sa_mask);
2032 sigaction(SIGCHLD, &sa, NULL);
2038 /* Don't get stuck if the resolver does not work! */
2039 signal(SIGALRM, palarm);
2041 sigaddset(&set, SIGALRM);
2042 (void)sigprocmask(SIG_UNBLOCK, &set, NULL);
2044 getremotehost(fds[1]);
2052 res = xread(fds[0], buf, sizeof(buf));
2055 wait_options = WNOHANG;
2060 strbuf_appendn(&hostname, buf, res);
2064 cleanup_push(&hostname, strbuf_cleanup);
2066 while ((wait_res = waitpid(pid, &status, wait_options)) == -1
2068 handle_pending_signals();
2069 if (hostname.len > 0 && wait_res == pid && WIFEXITED(status)
2070 && WEXITSTATUS(status) == 0) {
2071 strbuf_terminate(&hostname);
2072 tsetenv(STRREMOTEHOST, str2short(hostname.s));
2074 cleanup_until(&hostname);
2077 /* From: casper@fwi.uva.nl (Casper H.S. Dik), for Solaris 2.3 */
2082 #endif /* REMOTEHOST */
2084 #ifndef WINNT_NATIVE
2086 * indicate if a terminal type is defined in terminfo/termcap
2087 * (by default the current term type). This allows ppl to look
2088 * for a working term type automatically in their login scripts
2089 * when using a terminal known as different things on different
2093 dotermname(Char **v, struct command *c)
2097 * Maximum size of a termcap record. We make it twice as large.
2099 char termcap_buffer[2048];
2102 /* try to find which entry we should be looking for */
2103 termtype = (v[1] == NULL ? getenv("TERM") : short2str(v[1]));
2104 if (termtype == NULL) {
2105 /* no luck - the user didn't provide one and none is
2106 * specified in the environment
2108 setcopy(STRstatus, STR1, VAR_READWRITE);
2113 * we use the termcap function - if we are using terminfo we
2114 * will end up with it's compatibility function
2115 * terminfo/termcap will be initialized with the new
2116 * type but we don't care because tcsh has cached all the things
2119 if (tgetent(termcap_buffer, termtype) == 1) {
2120 xprintf("%s\n", termtype);
2121 setcopy(STRstatus, STR0, VAR_READWRITE);
2123 setcopy(STRstatus, STR1, VAR_READWRITE);
2125 #endif /* WINNT_NATIVE */