/contrib/tcsh/tc.func.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 2093 lines · 1594 code · 206 blank · 293 comment · 528 complexity · 7d47ad9d13582ffe2d054fc71282762f MD5 · raw file

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