1 /* $OpenBSD: misc.c,v 1.37 2009/04/19 20:34:05 sthen Exp $ */
2 /* $OpenBSD: path.c,v 1.12 2005/03/30 17:16:37 deraadt Exp $ */
5 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
7 * Thorsten Glaser <tg@mirbsd.org>
9 * Provided that these terms and disclaimer and all copyright notices
10 * are retained or reproduced in an accompanying document, permission
11 * is granted to deal in this work without restriction, including un-
12 * limited rights to use, publicly perform, distribute, sell, modify,
13 * merge, give away, or sublicence.
15 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
16 * the utmost extent permitted by applicable law, neither express nor
17 * implied; without malicious intent or gross negligence. In no event
18 * may a licensor, author or contributor be held liable for indirect,
19 * direct, other damage, loss, or other issues arising in any way out
20 * of dealing in the work, even if advised of the possibility of such
21 * damage or existence of a defect, except proven that it results out
22 * of said person's immediate fault when using the work as intended.
27 #include <sys/times.h>
33 __RCSID("$MirOS: src/bin/mksh/misc.c,v 1.214 2013/08/11 14:57:09 tg Exp $");
43 #ifdef MKSH_LEGACY_MODE
48 /* type bits for unsigned char */
49 unsigned char chtypes[UCHAR_MAX + 1];
51 static const unsigned char *pat_scan(const unsigned char *,
52 const unsigned char *, bool);
53 static int do_gmatch(const unsigned char *, const unsigned char *,
54 const unsigned char *, const unsigned char *);
55 static const unsigned char *cclass(const unsigned char *, unsigned char);
57 static void chvt(const Getopt *);
60 /*XXX this should go away */
61 static int make_path(const char *, const char *, char **, XString *, int *);
63 #ifdef SETUID_CAN_FAIL_WITH_EAGAIN
64 /* we don't need to check for other codes, EPERM won't happen */
65 #define DO_SETUID(func, argvec) do { \
66 if ((func argvec) && errno == EAGAIN) \
67 errorf("%s failed with EAGAIN, probably due to a" \
68 " too low process limit; aborting", #func); \
69 } while (/* CONSTCOND */ 0)
71 #define DO_SETUID(func, argvec) func argvec
75 * Fast character classes
78 setctypes(const char *s, int t)
83 for (i = 0; i < UCHAR_MAX + 1; i++)
85 /* include \0 in C_IFS */
89 chtypes[(unsigned char)*s++] |= t;
97 for (c = 'a'; c <= 'z'; c++)
98 chtypes[c] |= C_ALPHA;
99 for (c = 'A'; c <= 'Z'; c++)
100 chtypes[c] |= C_ALPHA;
101 chtypes['_'] |= C_ALPHA;
102 setctypes("0123456789", C_DIGIT);
103 /* \0 added automatically */
104 setctypes(TC_LEX1, C_LEX1);
105 setctypes("*@#!$-?", C_VAR1);
106 setctypes(TC_IFSWS, C_IFSWS);
107 setctypes("=-+?", C_SUBOP1);
108 setctypes("\t\n \"#$&'()*;<=>?[\\]`|", C_QUOTE);
111 /* called from XcheckN() to grow buffer */
113 Xcheck_grow(XString *xsp, const char *xp, size_t more)
115 const char *old_beg = xsp->beg;
119 /* (xsp->len + X_EXTRA) never overflows */
120 checkoktoadd(more, xsp->len + X_EXTRA);
121 xsp->beg = aresize(xsp->beg, (xsp->len += more) + X_EXTRA, xsp->areap);
122 xsp->end = xsp->beg + xsp->len;
123 return (xsp->beg + (xp - old_beg));
127 #define SHFLAGS_DEFNS
128 #include "sh_flags.h"
130 #define OFC(i) (options[i][-2])
131 #define OFF(i) (((const unsigned char *)options[i])[-1])
132 #define OFN(i) (options[i])
134 const char * const options[] = {
135 #define SHFLAGS_ITEMS
136 #include "sh_flags.h"
140 * translate -o option into F* constant (also used for test -o option)
143 option(const char *n)
147 if ((n[0] == '-' || n[0] == '+') && n[1] && !n[2])
148 while (i < NELEM(options)) {
154 while (i < NELEM(options)) {
155 if (!strcmp(OFN(i), n))
163 struct options_info {
165 int opts[NELEM(options)];
168 static char *options_fmt_entry(char *, size_t, unsigned int, const void *);
169 static void printoptions(bool);
171 /* format a single select menu item */
173 options_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
175 const struct options_info *oi = (const struct options_info *)arg;
177 shf_snprintf(buf, buflen, "%-*s %s",
178 oi->opt_width, OFN(oi->opts[i]),
179 Flag(oi->opts[i]) ? "on" : "off");
184 printoptions(bool verbose)
189 size_t n = 0, len, octs = 0;
190 struct options_info oi;
192 /* verbose version */
193 shf_puts("Current option settings\n", shl_stdout);
196 while (i < NELEM(options)) {
197 if ((len = strlen(OFN(i)))) {
201 len = utf_mbswidth(OFN(i));
202 if ((int)len > oi.opt_width)
203 oi.opt_width = (int)len;
207 print_columns(shl_stdout, n, options_fmt_entry, &oi,
208 octs + 4, oi.opt_width + 4, true);
210 /* short version like AT&T ksh93 */
211 shf_puts(Tset, shl_stdout);
212 while (i < NELEM(options)) {
213 if (Flag(i) && OFN(i)[0])
214 shprintf(" -o %s", OFN(i));
217 shf_putc('\n', shl_stdout);
225 char c, m[(int)FNFLAGS + 1];
228 while (i < NELEM(options)) {
229 if ((c = OFC(i)) && Flag(i))
233 strndupx(cp, m, cp - m, ATEMP);
237 /* change a Flag(*) value; takes care of special actions */
239 change_flag(enum sh_flag f, int what, bool newset)
241 unsigned char oldval;
242 unsigned char newval = (newset ? 1 : 0);
245 change_xtrace(newval, true);
249 Flag(f) = newval = (newset ? 1 : 0);
250 #ifndef MKSH_UNEMPLOYED
252 if (what != OF_CMDLINE && newval != oldval)
256 #ifndef MKSH_NO_CMDLINE_EDITING
261 f == FEMACS || f == FGMACS) && newval) {
265 Flag(FEMACS) = Flag(FGMACS) = 0;
269 if (f == FPRIVILEGED && oldval && !newval) {
270 /* Turning off -p? */
272 /*XXX this can probably be optimised */
273 kshegid = kshgid = getgid();
275 DO_SETUID(setresgid, (kshegid, kshegid, kshegid));
277 /* setgroups doesn't EAGAIN on Linux */
278 setgroups(1, &kshegid);
280 DO_SETUID(setresuid, (ksheuid, ksheuid, ksheuid));
282 /* seteuid, setegid, setgid don't EAGAIN on Linux */
283 ksheuid = kshuid = getuid();
284 #ifndef MKSH__NO_SETEUGID
287 DO_SETUID(setuid, (ksheuid));
288 #ifndef MKSH__NO_SETEUGID
293 } else if ((f == FPOSIX || f == FSH) && newval) {
294 /* Turning on -o posix or -o sh? */
295 Flag(FBRACEEXPAND) = 0;
296 } else if (f == FTALKING) {
297 /* Changing interactive flag? */
298 if ((what == OF_CMDLINE || what == OF_SET) && procpid == kshpid)
299 Flag(FTALKING_I) = newval;
304 change_xtrace(unsigned char newval, bool dosnapshot)
306 if (!dosnapshot && newval == Flag(FXTRACE))
309 if (Flag(FXTRACE) == 2) {
310 shf_putc('\n', shl_xtrace);
312 shf_flush(shl_xtrace);
315 if (!dosnapshot && Flag(FXTRACE) == 1)
323 shf_flush(shl_xtrace);
324 if (shl_xtrace->fd != 2)
325 close(shl_xtrace->fd);
326 if (!newval || (shl_xtrace->fd = savefd(2)) == -1)
330 if ((Flag(FXTRACE) = newval) == 2)
331 shf_puts(substitute(str_val(global("PS4")), 0), shl_xtrace);
335 * Parse command line and set command arguments. Returns the index of
336 * non-option arguments, -1 if there is an error.
339 parse_args(const char **argv,
340 /* OF_CMDLINE or OF_SET */
344 static char cmd_opts[NELEM(options) + 5]; /* o:T:\0 */
345 static char set_opts[NELEM(options) + 6]; /* A:o;s\0 */
348 const char *array = NULL;
351 int optc, arrayset = 0;
352 bool sortargs = false;
353 bool fcompatseen = false;
355 /* First call? Build option strings... */
356 if (cmd_opts[0] == '\0') {
357 char ch, *p = cmd_opts, *q = set_opts;
359 /* see cmd_opts[] declaration */
366 /* see set_opts[] declaration */
373 for (i = 0; i < NELEM(options); i++) {
375 if (OFF(i) & OF_CMDLINE)
385 if (what == OF_CMDLINE) {
386 const char *p = argv[0], *q;
388 * Set FLOGIN before parsing options so user can clear
395 Flag(FLOGIN) = (*p == '-');
397 } else if (what == OF_FIRSTTIME) {
401 ksh_getopt_reset(&go, GF_ERROR|GF_PLUSOPT);
402 while ((optc = ksh_getopt(argv, &go, opts)) != -1) {
403 set = tobool(!(go.info & GI_PLUS));
406 if (what == OF_FIRSTTIME)
408 arrayset = set ? 1 : -1;
413 if (what == OF_FIRSTTIME)
415 if (go.optarg == NULL) {
417 * lone -o: print options
419 * Note that on the command line, -o requires
420 * an option (ie, can't get here if what is
426 i = option(go.optarg);
427 if ((i == FPOSIX || i == FSH) && set && !fcompatseen) {
429 * If running 'set -o posix' or
430 * 'set -o sh', turn off the other;
431 * if running 'set -o posix -o sh'
432 * allow both to be set though.
438 if ((i != (size_t)-1) && (set ? 1U : 0U) == Flag(i))
440 * Don't check the context if the flag
441 * isn't changing - makes "set -o interactive"
442 * work if you're already interactive. Needed
443 * if the output of "set +o" is to be used.
446 else if ((i != (size_t)-1) && (OFF(i) & what))
447 change_flag((enum sh_flag)i, what, set);
449 bi_errorf("%s: %s", go.optarg, "bad option");
456 if (what != OF_FIRSTTIME)
458 #ifndef KSH_CHVT_CODE
459 errorf("no TIOCSCTTY ioctl");
461 change_flag(FTALKING, OF_CMDLINE, true);
471 if (what == OF_FIRSTTIME)
473 /* -s: sort positional params (AT&T ksh stupidity) */
474 if (what == OF_SET && optc == 's') {
478 for (i = 0; i < NELEM(options); i++)
479 if (optc == OFC(i) &&
481 change_flag((enum sh_flag)i, what, set);
484 if (i == NELEM(options))
485 internal_errorf("parse_args: '%c'", optc);
488 if (!(go.info & GI_MINUSMINUS) && argv[go.optind] &&
489 (argv[go.optind][0] == '-' || argv[go.optind][0] == '+') &&
490 argv[go.optind][1] == '\0') {
491 /* lone - clears -v and -x flags */
492 if (argv[go.optind][0] == '-') {
494 change_xtrace(0, false);
496 /* set skips lone - or + option */
500 /* -- means set $#/$* even if there are no arguments */
501 *setargsp = !arrayset && ((go.info & GI_MINUSMINUS) ||
505 const char *ccp = NULL;
507 mkssert(array != NULL);
509 ccp = skip_varname(array, false);
510 if (!ccp || !(!ccp[0] || (ccp[0] == '+' && !ccp[1]))) {
511 bi_errorf("%s: %s", array, "is not an identifier");
516 for (i = go.optind; argv[i]; i++)
518 qsort(&argv[go.optind], i - go.optind, sizeof(void *),
522 go.optind += set_array(array, tobool(arrayset > 0),
528 /* parse a decimal number: returns 0 if string isn't a number, 1 otherwise */
530 getn(const char *s, int *ai)
540 } while (ksh_isspace(c));
555 if (num.u > 214748364U)
556 /* overflow on multiplication */
558 num.u = num.u * 10U + (unsigned int)(c - '0');
559 /* now: num.u <= 2147483649U */
560 } while ((c = *s++));
562 if (num.u > (neg ? 2147483648U : 2147483647U))
563 /* overflow for signed 32-bit int */
573 * pattern simplifications:
574 * - @(x) -> x (not @(x|y) though)
578 simplify_gmatch_pattern(const unsigned char *sp)
581 unsigned char *cp, *dp;
582 const unsigned char *ps, *se;
584 cp = alloc(strlen((const void *)sp) + 1, ATEMP);
585 goto simplify_gmatch_pat1a;
587 /* foo@(b@(a)r)b@(a|a)z -> foobarb@(a|a)z */
588 simplify_gmatch_pat1:
590 simplify_gmatch_pat1a:
592 se = sp + strlen((const void *)sp);
593 while ((c = *sp++)) {
598 switch ((c = *sp++)) {
602 /* check whether it has only one clause */
603 ps = pat_scan(sp, se, true);
604 if (!ps || ps[-1] != /*(*/ ')')
607 /* copy inner clause until matching close */
609 while ((const unsigned char *)sp < ps)
611 /* skip MAGIC and closing parenthesis */
613 /* copy the rest of the pattern */
614 memmove(dp, sp, strlen((const void *)sp) + 1);
615 /* redo from start */
616 goto simplify_gmatch_pat1;
623 /* collapse adjacent asterisk wildcards */
625 while ((c = *sp++)) {
630 switch ((c = *sp++)) {
632 while (ISMAGIC(sp[0]) && sp[1] == c)
641 /* return the result, allocated from ATEMP */
645 /* -------- gmatch.c -------- */
648 * int gmatch(string, pattern)
649 * char *string, *pattern;
651 * Match a pattern as in sh(1).
652 * pattern character are prefixed with MAGIC by expand.
655 gmatchx(const char *s, const char *p, bool isfile)
661 if (s == NULL || p == NULL)
667 * isfile is false iff no syntax check has been done on
668 * the pattern. If check fails, just to a strcmp().
670 if (!isfile && !has_globbing(p, pe)) {
671 size_t len = pe - p + 1;
673 char *t = len <= sizeof(tbuf) ? tbuf : alloc(len, ATEMP);
675 return (!strcmp(t, s));
679 * since the do_gmatch() engine sucks so much, we must do some
680 * pattern simplifications
682 pnew = simplify_gmatch_pattern((const unsigned char *)p);
683 pe = pnew + strlen(pnew);
685 rv = do_gmatch((const unsigned char *)s, (const unsigned char *)se,
686 (const unsigned char *)pnew, (const unsigned char *)pe);
692 * Returns if p is a syntacticly correct globbing pattern, false
693 * if it contains no pattern characters or if there is a syntax error.
695 * - [ with no closing ]
696 * - imbalanced $(...) expression
697 * - [...] and *(...) not nested (eg, [a$(b|]c), *(a[b|c]d))
701 * if dest given, copy to dst
703 * - if magic && (no globbing || syntax error)
709 has_globbing(const char *xp, const char *xpe)
711 const unsigned char *p = (const unsigned char *) xp;
712 const unsigned char *pe = (const unsigned char *) xpe;
714 int nest = 0, bnest = 0;
715 bool saw_glob = false;
717 bool in_bracket = false;
719 for (; p < pe; p++) {
722 if ((c = *++p) == '*' || c == '?')
728 if (ISMAGIC(p[1]) && p[2] == '!')
730 if (ISMAGIC(p[1]) && p[2] == ']')
733 /*XXX Do we need to check ranges here? POSIX Q */
734 } else if (c == ']') {
741 } else if ((c & 0x80) && vstrchr("*+?@! ", c & 0x7f)) {
747 } else if (c == '|') {
748 if (in_bracket && !bnest)
751 } else if (c == /*(*/ ')') {
760 * else must be a MAGIC-MAGIC, or MAGIC-!,
761 * MAGIC--, MAGIC-], MAGIC-{, MAGIC-, MAGIC-}
764 return (saw_glob && !in_bracket && !nest);
767 /* Function must return either 0 or 1 (assumed by code for 0x80|'!') */
769 do_gmatch(const unsigned char *s, const unsigned char *se,
770 const unsigned char *p, const unsigned char *pe)
772 unsigned char sc, pc;
773 const unsigned char *prest, *psub, *pnext;
774 const unsigned char *srest;
776 if (s == NULL || p == NULL)
780 sc = s < se ? *s : '\0';
789 if (sc == 0 || (p = cclass(p, sc)) == NULL)
798 s += utf_ptradj((const void *)s);
807 if (do_gmatch(s, se, p, pe))
813 * [*+?@!](pattern|pattern|..)
814 * This is also needed for ${..%..}, etc.
817 /* matches one or more times */
819 /* matches zero or more times */
821 if (!(prest = pat_scan(p, pe, false)))
824 /* take care of zero matches */
825 if (p[-1] == (0x80 | '*') &&
826 do_gmatch(s, se, prest, pe))
828 for (psub = p; ; psub = pnext) {
829 pnext = pat_scan(psub, pe, true);
830 for (srest = s; srest <= se; srest++) {
831 if (do_gmatch(s, srest, psub, pnext - 2) &&
832 (do_gmatch(srest, se, prest, pe) ||
833 (s != srest && do_gmatch(srest,
842 /* matches zero or once */
844 /* matches one of the patterns */
848 if (!(prest = pat_scan(p, pe, false)))
851 /* Take care of zero matches */
852 if (p[-1] == (0x80 | '?') &&
853 do_gmatch(s, se, prest, pe))
855 for (psub = p; ; psub = pnext) {
856 pnext = pat_scan(psub, pe, true);
857 srest = prest == pe ? se : s;
858 for (; srest <= se; srest++) {
859 if (do_gmatch(s, srest, psub, pnext - 2) &&
860 do_gmatch(srest, se, prest, pe))
868 /* matches none of the patterns */
870 if (!(prest = pat_scan(p, pe, false)))
873 for (srest = s; srest <= se; srest++) {
876 for (psub = p; ; psub = pnext) {
877 pnext = pat_scan(psub, pe, true);
878 if (do_gmatch(s, srest, psub,
887 do_gmatch(srest, se, prest, pe))
901 static const unsigned char *
902 cclass(const unsigned char *p, unsigned char sub)
905 bool notp, found = false;
906 const unsigned char *orig_p = p;
908 if ((notp = tobool(ISMAGIC(*p) && *++p == '!')))
914 if ((c & 0x80) && !ISMAGIC(c)) {
915 /* extended pattern matching: *+?@! */
917 /* XXX the ( char isn't handled as part of [] */
919 /* simile for @: plain (..) */
924 /* No closing ] - act as if the opening [ was quoted */
925 return (sub == '[' ? orig_p : NULL);
926 if (ISMAGIC(p[0]) && p[1] == '-' &&
927 (!ISMAGIC(p[2]) || p[3] != ']')) {
933 if ((d & 0x80) && !ISMAGIC(d))
936 /* POSIX says this is an invalid expression */
941 if (c == sub || (c <= sub && sub <= d))
943 } while (!(ISMAGIC(p[0]) && p[1] == ']'));
945 return ((found != notp) ? p+2 : NULL);
948 /* Look for next ) or | (if match_sep) in *(foo|bar) pattern */
949 static const unsigned char *
950 pat_scan(const unsigned char *p, const unsigned char *pe, bool match_sep)
954 for (; p < pe; p++) {
957 if ((*++p == /*(*/ ')' && nest-- == 0) ||
958 (*p == '|' && match_sep && nest == 0))
960 if ((*p & 0x80) && vstrchr("*+?@! ", *p & 0x7f))
967 xstrcmp(const void *p1, const void *p2)
969 return (strcmp(*(const char * const *)p1, *(const char * const *)p2));
972 /* Initialise a Getopt structure */
974 ksh_getopt_reset(Getopt *go, int flags)
986 * getopt() used for shell built-in commands, the getopts command, and
987 * command line options.
988 * A leading ':' in options means don't print errors, instead return '?'
989 * or ':' and set go->optarg to the offending option character.
990 * If GF_ERROR is set (and option doesn't start with :), errors result in
991 * a call to bi_errorf().
993 * Non-standard features:
994 * - ';' is like ':' in options, except the argument is optional
995 * (if it isn't present, optarg is set to 0).
997 * - ',' is like ':' in options, except the argument always immediately
998 * follows the option character (optarg is set to the null string if
999 * the option is missing).
1000 * Used for 'read -u2', 'print -u2' and fc -40.
1001 * - '#' is like ':' in options, expect that the argument is optional
1002 * and must start with a digit. If the argument doesn't start with a
1003 * digit, it is assumed to be missing and normal option processing
1004 * continues (optarg is set to 0 if the option is missing).
1005 * Used for 'typeset -LZ4'.
1006 * - accepts +c as well as -c IF the GF_PLUSOPT flag is present. If an
1007 * option starting with + is accepted, the GI_PLUS flag will be set
1011 ksh_getopt(const char **argv, Getopt *go, const char *optionsp)
1016 if (go->p == 0 || (c = argv[go->optind - 1][go->p]) == '\0') {
1017 const char *arg = argv[go->optind], flag = arg ? *arg : '\0';
1020 if (flag == '-' && arg[1] == '-' && arg[2] == '\0') {
1023 go->info |= GI_MINUSMINUS;
1028 /* neither a - nor a + (if + allowed) */
1029 (!(go->flags & GF_PLUSOPT) || flag != '+')) ||
1030 (c = arg[1]) == '\0') {
1035 go->info &= ~(GI_MINUS|GI_PLUS);
1036 go->info |= flag == '-' ? GI_MINUS : GI_PLUS;
1039 if (c == '?' || c == ':' || c == ';' || c == ',' || c == '#' ||
1040 !(o = cstrchr(optionsp, c))) {
1041 if (optionsp[0] == ':') {
1043 go->optarg = go->buf;
1045 warningf(true, "%s%s-%c: %s",
1046 (go->flags & GF_NONAME) ? "" : argv[0],
1047 (go->flags & GF_NONAME) ? "" : ": ", c,
1049 if (go->flags & GF_ERROR)
1055 * : means argument must be present, may be part of option argument
1056 * or the next argument
1057 * ; same as : but argument may be missing
1058 * , means argument is part of option argument, and may be null.
1060 if (*++o == ':' || *o == ';') {
1061 if (argv[go->optind - 1][go->p])
1062 go->optarg = argv[go->optind - 1] + go->p;
1063 else if (argv[go->optind])
1064 go->optarg = argv[go->optind++];
1068 if (optionsp[0] == ':') {
1070 go->optarg = go->buf;
1073 warningf(true, "%s%s-%c: %s",
1074 (go->flags & GF_NONAME) ? "" : argv[0],
1075 (go->flags & GF_NONAME) ? "" : ": ", c,
1076 "requires an argument");
1077 if (go->flags & GF_ERROR)
1082 } else if (*o == ',') {
1083 /* argument is attached to option character, even if null */
1084 go->optarg = argv[go->optind - 1] + go->p;
1086 } else if (*o == '#') {
1088 * argument is optional and may be attached or unattached
1089 * but must start with a digit. optarg is set to 0 if the
1090 * argument is missing.
1092 if (argv[go->optind - 1][go->p]) {
1093 if (ksh_isdigit(argv[go->optind - 1][go->p])) {
1094 go->optarg = argv[go->optind - 1] + go->p;
1099 if (argv[go->optind] && ksh_isdigit(argv[go->optind][0])) {
1100 go->optarg = argv[go->optind++];
1110 * print variable/alias value using necessary quotes
1111 * (POSIX says they should be suitable for re-entry...)
1112 * No trailing newline is printed.
1115 print_value_quoted(struct shf *shf, const char *s)
1118 const unsigned char *p = (const unsigned char *)s;
1119 bool inquote = true;
1121 /* first, check whether any quotes are needed */
1122 while ((c = *p++) >= 32)
1123 if (ctype(c, C_QUOTE))
1126 p = (const unsigned char *)s;
1129 /* nope, use the shortcut */
1134 /* otherwise, quote nicely via state machine */
1135 while ((c = *p++) != 0) {
1138 * multiple single quotes or any of them
1139 * at the beginning of a string look nicer
1140 * this way than when simply substituting
1143 shf_putc('\'', shf);
1146 shf_putc('\\', shf);
1147 } else if (!inquote) {
1148 shf_putc('\'', shf);
1157 /* use $'...' quote format */
1159 shf_putc('\'', shf);
1160 while ((c = *p) != 0) {
1162 n = utf_mbtowc(&wc, (const char *)p);
1163 if (n != (size_t)-1) {
1165 shf_fprintf(shf, "\\u%04X", wc);
1171 /* see unbksl() in this file for comments */
1201 /* take E not e because \e is \ in *roff */
1205 shf_putc('\\', shf);
1210 if (c < 32 || c > 0x7E) {
1213 shf_fprintf(shf, "\\%03o", c);
1224 shf_putc('\'', shf);
1228 * Print things in columns and rows - func() is called to format
1232 print_columns(struct shf *shf, unsigned int n,
1233 char *(*func)(char *, size_t, unsigned int, const void *),
1234 const void *arg, size_t max_oct, size_t max_colz, bool prefcol)
1236 unsigned int i, r, c, rows, cols, nspace, max_col;
1242 if (max_colz > 2147483646) {
1244 internal_warningf("print_columns called with %s=%zu >= INT_MAX",
1245 "max_col", max_colz);
1249 max_col = (unsigned int)max_colz;
1251 if (max_oct > 2147483646) {
1253 internal_warningf("print_columns called with %s=%zu >= INT_MAX",
1254 "max_oct", max_oct);
1259 str = alloc(max_oct, ATEMP);
1262 * We use (max_col + 1) to consider the space separator.
1263 * Note that no space is printed after the last column
1264 * to avoid problems with terminals that have auto-wrap.
1266 cols = x_cols / (max_col + 1);
1268 /* if we can only print one column anyway, skip the goo */
1270 for (i = 0; i < n; ++i)
1271 shf_fprintf(shf, "%s\n",
1272 (*func)(str, max_oct, i, arg));
1276 rows = (n + cols - 1) / cols;
1277 if (prefcol && cols > rows) {
1279 rows = (n + cols - 1) / cols;
1282 nspace = (x_cols - max_col * cols) / cols;
1286 for (r = 0; r < rows; r++) {
1287 for (c = 0; c < cols; c++) {
1290 shf_fprintf(shf, "%*s", max_col,
1291 (*func)(str, max_oct, i, arg));
1293 shf_fprintf(shf, "%*s", nspace, null);
1296 shf_putchar('\n', shf);
1302 /* Strip any nul bytes from buf - returns new length (nbytes - # of nuls) */
1304 strip_nuls(char *buf, int nbytes)
1309 * nbytes check because some systems (older FreeBSDs) have a
1312 if (nbytes && (dst = memchr(buf, '\0', nbytes))) {
1313 char *end = buf + nbytes;
1316 for (p = dst; p < end; p = q) {
1317 /* skip a block of nulls */
1318 while (++p < end && *p == '\0')
1320 /* find end of non-null block */
1321 if (!(q = memchr(p, '\0', end - p)))
1323 memmove(dst, p, q - p);
1331 * Like read(2), but if read fails due to non-blocking flag,
1332 * resets flag and restarts read.
1335 blocking_read(int fd, char *buf, size_t nbytes)
1338 bool tried_reset = false;
1340 while ((ret = read(fd, buf, nbytes)) < 0) {
1341 if (!tried_reset && errno == EAGAIN) {
1342 if (reset_nonblock(fd) > 0) {
1354 * Reset the non-blocking flag on the specified file descriptor.
1355 * Returns -1 if there was an error, 0 if non-blocking wasn't set,
1359 reset_nonblock(int fd)
1363 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1365 if (!(flags & O_NONBLOCK))
1367 flags &= ~O_NONBLOCK;
1368 if (fcntl(fd, F_SETFL, flags) < 0)
1373 /* getcwd(3) equivalent, allocates from ATEMP but doesn't resize */
1377 #ifdef MKSH__NO_PATH_MAX
1380 if ((cp = get_current_dir_name())) {
1381 strdupx(rv, cp, ATEMP);
1388 if (!getcwd((rv = alloc(PATH_MAX + 1, ATEMP)), PATH_MAX)) {
1402 do_realpath(const char *upath)
1404 char *xp, *ip, *tp, *ipath, *ldest = NULL;
1410 #ifdef MKSH__NO_PATH_MAX
1411 size_t ldestlen = 0;
1412 #define pathlen sb.st_size
1413 #define pathcnd (ldestlen < (pathlen + 1))
1415 #define pathlen PATH_MAX
1416 #define pathcnd (!ldest)
1418 /* max. recursion depth */
1421 if (upath[0] == '/') {
1422 /* upath is an absolute pathname */
1423 strdupx(ipath, upath, ATEMP);
1425 /* upath is a relative pathname, prepend cwd */
1426 if ((tp = ksh_get_wd()) == NULL || tp[0] != '/')
1428 ipath = shf_smprintf("%s%s%s", tp, "/", upath);
1432 /* ipath and upath are in memory at the same time -> unchecked */
1433 Xinit(xs, xp, strlen(ip = ipath) + 1, ATEMP);
1435 /* now jump into the deep of the loop */
1436 goto beginning_of_a_pathname;
1439 /* skip slashes in input */
1445 /* get next pathname component from input */
1447 while (*ip && *ip != '/')
1451 /* check input for "." and ".." */
1454 /* just continue with the next one */
1456 else if (len == 2 && tp[1] == '.') {
1457 /* strip off last pathname component */
1458 while (xp > Xstring(xs, xp))
1461 /* then continue with the next one */
1466 /* store output position away, then append slash to output */
1467 pos = Xsavepos(xs, xp);
1468 /* 1 for the '/' and len + 1 for tp and the NUL from below */
1469 XcheckN(xs, xp, 1 + len + 1);
1472 /* append next pathname component to output */
1473 memcpy(xp, tp, len);
1477 /* lstat the current output, see if it's a symlink */
1478 if (mksh_lstat(Xstring(xs, xp), &sb)) {
1480 if (errno == ENOENT) {
1481 /* because the pathname does not exist */
1483 /* skip any trailing slashes */
1485 /* no more components left? */
1487 /* we can still return successfully */
1489 /* more components left? fall through */
1491 /* not ENOENT or not at the end of ipath */
1495 /* check if we encountered a symlink? */
1496 if (S_ISLNK(sb.st_mode)) {
1497 #ifndef MKSH__NO_SYMLINK
1498 /* reached maximum recursion depth? */
1500 /* yep, prevent infinite loops */
1505 /* get symlink(7) target */
1507 #ifdef MKSH__NO_PATH_MAX
1508 if (notoktoadd(pathlen, 1)) {
1509 errno = ENAMETOOLONG;
1513 ldest = aresize(ldest, pathlen + 1, ATEMP);
1515 llen = readlink(Xstring(xs, xp), ldest, pathlen);
1522 * restart if symlink target is an absolute path,
1523 * otherwise continue with currently resolved prefix
1525 /* append rest of current input path to link target */
1526 tp = shf_smprintf("%s%s%s", ldest, *ip ? "/" : "", ip);
1527 afree(ipath, ATEMP);
1529 if (ldest[0] != '/') {
1530 /* symlink target is a relative path */
1531 xp = Xrestpos(xs, xp, pos);
1535 /* symlink target is an absolute path */
1536 xp = Xstring(xs, xp);
1537 beginning_of_a_pathname:
1538 /* assert: (ip == ipath)[0] == '/' */
1539 /* assert: xp == xs.beg => start of path */
1541 /* exactly two leading slashes? (SUSv4 3.266) */
1542 if (ip[1] == '/' && ip[2] != '/') {
1543 /* keep them, e.g. for UNC pathnames */
1548 /* otherwise (no symlink) merely go on */
1552 * either found the target and successfully resolved it,
1553 * or found its parent directory and may create it
1555 if (Xlength(xs, xp) == 0)
1557 * if the resolved pathname is "", make it "/",
1558 * otherwise do not add a trailing slash
1564 * if source path had a trailing slash, check if target path
1565 * is not a non-directory existing file
1567 if (ip > ipath && ip[-1] == '/') {
1568 if (stat(Xstring(xs, xp), &sb)) {
1569 if (errno != ENOENT)
1571 } else if (!S_ISDIR(sb.st_mode)) {
1575 /* target now either does not exist or is a directory */
1578 /* return target path */
1580 afree(ldest, ATEMP);
1581 afree(ipath, ATEMP);
1582 return (Xclose(xs, xp));
1585 /* save; freeing memory might trash it */
1588 afree(ldest, ATEMP);
1589 afree(ipath, ATEMP);
1599 * Makes a filename into result using the following algorithm.
1600 * - make result NULL
1601 * - if file starts with '/', append file to result & set cdpathp to NULL
1602 * - if file starts with ./ or ../ append cwd and file to result
1603 * and set cdpathp to NULL
1604 * - if the first element of cdpathp doesnt start with a '/' xx or '.' xx
1605 * then cwd is appended to result.
1606 * - the first element of cdpathp is appended to result
1607 * - file is appended to result
1608 * - cdpathp is set to the start of the next element in cdpathp (or NULL
1609 * if there are no more elements.
1610 * The return value indicates whether a non-null element from cdpathp
1611 * was appended to result.
1614 make_path(const char *cwd, const char *file,
1615 /* pointer to colon-separated list */
1621 bool use_cdpath = true;
1623 size_t len, plen = 0;
1624 char *xp = Xstring(*xsp, xp);
1629 if (file[0] == '/') {
1633 if (file[0] == '.') {
1638 if (c == '/' || c == '\0')
1645 else if (use_cdpath) {
1648 for (pend = plist; *pend && *pend != ':'; pend++)
1650 plen = pend - plist;
1651 *cdpathp = *pend ? pend + 1 : NULL;
1654 if ((!use_cdpath || !plen || plist[0] != '/') &&
1657 XcheckN(*xsp, xp, len);
1658 memcpy(xp, cwd, len);
1660 if (cwd[len - 1] != '/')
1661 Xput(*xsp, xp, '/');
1663 *phys_pathp = Xlength(*xsp, xp);
1664 if (use_cdpath && plen) {
1665 XcheckN(*xsp, xp, plen);
1666 memcpy(xp, plist, plen);
1668 if (plist[plen - 1] != '/')
1669 Xput(*xsp, xp, '/');
1674 len = strlen(file) + 1;
1675 XcheckN(*xsp, xp, len);
1676 memcpy(xp, file, len);
1685 * Simplify pathnames containing "." and ".." entries.
1687 * simplify_path(this) = that
1688 * /a/b/c/./../d/.. /a/b
1689 * //./C/foo/bar/../baz //C/foo/baz
1691 * /foo/../../bar /bar
1692 * /foo/./blah/.. /foo
1696 * foo/../../../bar ../../bar
1699 simplify_path(char *p)
1701 char *dp, *ip, *sp, *tp;
1709 /* exactly two leading slashes? (SUSv4 3.266) */
1710 if (p[1] == '/' && p[2] != '/')
1711 /* keep them, e.g. for UNC pathnames */
1721 /* skip slashes in input */
1727 /* get next pathname component from input */
1729 while (*ip && *ip != '/')
1733 /* check input for "." and ".." */
1736 /* just continue with the next one */
1738 else if (len == 2 && tp[1] == '.') {
1739 /* parent level, but how? */
1741 /* absolute path, only one way */
1742 goto strip_last_component;
1744 /* relative path, with subpaths */
1746 strip_last_component:
1747 /* strip off last pathname component */
1752 /* relative path, at its beginning */
1754 /* or already dotdot-slash'd */
1756 /* keep dotdot-slash if not absolute */
1762 /* then continue with the next one */
1770 /* append next pathname component to output */
1771 memmove(dp, tp, len);
1774 /* append slash if we continue */
1776 /* try next component */
1779 /* empty path -> dot */
1780 *dp++ = needslash ? '/' : '.';
1785 set_current_wd(const char *nwd)
1787 char *allocd = NULL;
1790 allocd = ksh_get_wd();
1791 nwd = allocd ? allocd : null;
1794 afree(current_wd, APERM);
1795 strdupx(current_wd, nwd, APERM);
1797 afree(allocd, ATEMP);
1801 c_cd(const char **wp)
1803 int optc, rv, phys_path;
1804 bool physical = tobool(Flag(FPHYSICAL));
1805 /* was a node from cdpath added in? */
1807 /* show where we went?, error for $PWD */
1808 bool printpath = false, eflag = false;
1809 struct tbl *pwd_s, *oldpwd_s;
1811 char *dir, *allocd = NULL, *tryp, *pwd, *cdpath;
1813 while ((optc = ksh_getopt(wp, &builtin_opt, "eLP")) != -1)
1827 wp += builtin_opt.optind;
1829 if (Flag(FRESTRICTED)) {
1830 bi_errorf("restricted shell - can't cd");
1834 pwd_s = global("PWD");
1835 oldpwd_s = global("OLDPWD");
1838 /* No arguments - go home */
1839 if ((dir = str_val(global("HOME"))) == null) {
1840 bi_errorf("no home directory (HOME not set)");
1843 } else if (!wp[1]) {
1844 /* One argument: - or dir */
1845 strdupx(allocd, wp[0], ATEMP);
1846 if (ksh_isdash((dir = allocd))) {
1847 afree(allocd, ATEMP);
1849 dir = str_val(oldpwd_s);
1851 bi_errorf("no OLDPWD");
1856 } else if (!wp[2]) {
1857 /* Two arguments - substitute arg1 in PWD for arg2 */
1858 size_t ilen, olen, nlen, elen;
1861 if (!current_wd[0]) {
1862 bi_errorf("can't determine current directory");
1866 * substitute arg1 for arg2 in current path.
1867 * if the first substitution fails because the cd fails
1868 * we could try to find another substitution. For now
1871 if ((cp = strstr(current_wd, wp[0])) == NULL) {
1872 bi_errorf("bad substitution");
1876 * ilen = part of current_wd before wp[0]
1877 * elen = part of current_wd after wp[0]
1878 * because current_wd and wp[1] need to be in memory at the
1879 * same time beforehand the addition can stay unchecked
1881 ilen = cp - current_wd;
1882 olen = strlen(wp[0]);
1883 nlen = strlen(wp[1]);
1884 elen = strlen(current_wd + ilen + olen) + 1;
1885 dir = allocd = alloc(ilen + nlen + elen, ATEMP);
1886 memcpy(dir, current_wd, ilen);
1887 memcpy(dir + ilen, wp[1], nlen);
1888 memcpy(dir + ilen + nlen, current_wd + ilen + olen, elen);
1891 bi_errorf("too many arguments");
1895 #ifdef MKSH__NO_PATH_MAX
1896 /* only a first guess; make_path will enlarge xs if necessary */
1897 XinitN(xs, 1024, ATEMP);
1899 XinitN(xs, PATH_MAX, ATEMP);
1902 cdpath = str_val(global("CDPATH"));
1904 cdnode = make_path(current_wd, dir, &cdpath, &xs, &phys_path);
1906 rv = chdir(tryp = Xstring(xs, xp) + phys_path);
1908 simplify_path(Xstring(xs, xp));
1909 rv = chdir(tryp = Xstring(xs, xp));
1911 } while (rv < 0 && cdpath != NULL);
1915 bi_errorf("%s: %s", dir, "bad directory");
1917 bi_errorf("%s: %s", tryp, cstrerror(errno));
1918 afree(allocd, ATEMP);
1925 /* allocd (above) => dir, which is no longer used */
1926 afree(allocd, ATEMP);
1929 /* Clear out tracked aliases with relative paths */
1933 * Set OLDPWD (note: unsetting OLDPWD does not disable this
1934 * setting in AT&T ksh)
1937 /* Ignore failure (happens if readonly or integer) */
1938 setstr(oldpwd_s, current_wd, KSH_RETURN_ERROR);
1940 if (Xstring(xs, xp)[0] != '/') {
1942 } else if (!physical) {
1943 goto norealpath_PWD;
1944 } else if ((pwd = allocd = do_realpath(Xstring(xs, xp))) == NULL) {
1948 pwd = Xstring(xs, xp);
1955 set_current_wd(ptmp);
1956 /* Ignore failure (happens if readonly or integer) */
1957 setstr(pwd_s, ptmp, KSH_RETURN_ERROR);
1959 set_current_wd(null);
1960 pwd = Xstring(xs, xp);
1961 /* XXX unset $PWD? */
1965 if (printpath || cdnode)
1966 shprintf("%s\n", pwd);
1968 afree(allocd, ATEMP);
1974 #ifdef KSH_CHVT_CODE
1975 extern uint32_t chvt_rndsetup(const void *, size_t);
1976 extern void chvt_reinit(void);
1979 chvt(const Getopt *go)
1981 const char *dv = go->optarg;
1995 if (stat(dv, &sb)) {
1996 cp = shf_smprintf("/dev/ttyC%s", dv);
1998 if (stat(dv, &sb)) {
1999 memmove(cp + 1, cp, /* /dev/tty */ 8);
2001 if (stat(dv, &sb)) {
2002 errorf("%s: %s: %s", "chvt",
2003 "can't find tty", go->optarg);
2007 if (!(sb.st_mode & S_IFCHR))
2008 errorf("%s: %s: %s", "chvt", "not a char device", dv);
2009 #ifndef MKSH_DISABLE_REVOKE_WARNING
2013 warningf(false, "%s: %s %s", "chvt",
2014 "new shell is potentially insecure, can't revoke",
2019 if ((fd = open(dv, O_RDWR)) < 0) {
2021 if ((fd = open(dv, O_RDWR)) < 0) {
2022 errorf("%s: %s %s", "chvt", "can't open", dv);
2025 if (go->optarg[0] != '!') {
2028 errorf("%s: %s %s", "chvt", "fork", "failed");
2036 errorf("%s: %s %s", "chvt", "setsid", "failed");
2037 if (go->optarg[0] != '-') {
2038 if (ioctl(fd, TIOCSCTTY, NULL) == -1)
2039 errorf("%s: %s %s", "chvt", "TIOCSCTTY", "failed");
2040 if (tcflush(fd, TCIOFLUSH))
2041 errorf("%s: %s %s", "chvt", "TCIOFLUSH", "failed");
2043 ksh_dup2(fd, 0, false);
2044 ksh_dup2(fd, 1, false);
2045 ksh_dup2(fd, 2, false);
2048 rndset((unsigned long)chvt_rndsetup(go, sizeof(Getopt)));
2055 strchr(char *p, int ch)
2067 strstr(char *b, const char *l)
2072 if ((first = *l++) == '\0')
2076 while ((c = *b++) != first)
2079 if (strncmp(b, l, n))
2085 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
2087 strndup_i(const char *src, size_t len, Area *ap)
2092 dst = alloc(len + 1, ap);
2093 memcpy(dst, src, len);
2100 strdup_i(const char *src, Area *ap)
2102 return (src == NULL ? NULL : strndup_i(src, strlen(src), ap));
2107 #define INVTCK(r,t) do { \
2108 r.tv_usec = ((t) % (1000000 / CLK_TCK)) * (1000000 / CLK_TCK); \
2109 r.tv_sec = (t) / CLK_TCK; \
2110 } while (/* CONSTCOND */ 0)
2113 getrusage(int what, struct rusage *ru)
2118 if (/* ru == NULL || */ times(&tms) == (clock_t)-1)
2126 case RUSAGE_CHILDREN:
2134 INVTCK(ru->ru_utime, u);
2135 INVTCK(ru->ru_stime, s);
2141 * process the string available via fg (get a char)
2142 * and fp (put back a char) for backslash escapes,
2143 * assuming the first call to *fg gets the char di-
2144 * rectly after the backslash; return the character
2145 * (0..0xFF), Unicode (wc + 0x100), or -1 if no known
2146 * escape sequence was found
2149 unbksl(bool cstyle, int (*fg)(void), void (*fp)(int))
2157 * according to the comments in pdksh, \007 seems
2158 * to be more portable than \a (due to HP-UX cc,
2159 * Ultrix cc, old pcc, etc.) so we avoid the escape
2160 * sequence altogether in mksh and assume ASCII
2169 goto unknown_escape;
2190 /* assume ASCII here as well */
2201 goto unknown_escape;
2207 * look for an octal number with up to three
2208 * digits, not counting the leading zero;
2209 * convert it to a raw octet
2214 if ((c = (*fg)()) >= '0' && c <= '7')
2215 wc = (wc << 3) + (c - '0');
2223 if (/* CONSTCOND */ 0)
2227 if (/* CONSTCOND */ 0)
2230 i = cstyle ? -1 : 2;
2232 * x: look for a hexadecimal number with up to
2233 * two (C style: arbitrary) digits; convert
2234 * to raw octet (C style: Unicode if >0xFF)
2235 * u/U: look for a hexadecimal number with up to
2236 * four (U: eight) digits; convert to Unicode
2241 if ((c = (*fg)()) >= '0' && c <= '9')
2243 else if (c >= 'A' && c <= 'F')
2245 else if (c >= 'a' && c <= 'f')
2253 if ((cstyle && wc > 0xFF) || fc != 'x')
2254 /* Unicode marker */
2259 goto unknown_escape;