1 /* $OpenBSD: misc.c,v 1.41 2015/09/10 22:48:58 nicm Exp $ */
2 /* $OpenBSD: path.c,v 1.13 2015/09/05 09:47:08 jsg Exp $ */
5 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
6 * 2011, 2012, 2013, 2014, 2015, 2016
7 * mirabilos <m@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.249 2016/11/11 23:31:35 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) MKSH_A_PURE;
53 static int do_gmatch(const unsigned char *, const unsigned char *,
54 const unsigned char *, const unsigned char *) MKSH_A_PURE;
55 static const unsigned char *gmatch_cclass(const unsigned char *, unsigned char)
58 static void chvt(const Getopt *);
61 /*XXX this should go away */
62 static int make_path(const char *, const char *, char **, XString *, int *);
64 #ifdef SETUID_CAN_FAIL_WITH_EAGAIN
65 /* we don't need to check for other codes, EPERM won't happen */
66 #define DO_SETUID(func, argvec) do { \
67 if ((func argvec) && errno == EAGAIN) \
68 errorf("%s failed with EAGAIN, probably due to a" \
69 " too low process limit; aborting", #func); \
70 } while (/* CONSTCOND */ 0)
72 #define DO_SETUID(func, argvec) func argvec
76 * Fast character classes
79 setctypes(const char *s, int t)
84 while (++i <= UCHAR_MAX)
86 /* include '\0' in C_IFS */
90 chtypes[(unsigned char)*s++] |= t;
96 setctypes(letters_uc, C_ALPHA);
97 setctypes(letters_lc, C_ALPHA);
98 chtypes['_'] |= C_ALPHA;
99 setctypes("0123456789", C_DIGIT);
100 /* \0 added automatically */
101 setctypes(TC_LEX1, C_LEX1);
102 setctypes("*@#!$-?", C_VAR1);
103 setctypes(TC_IFSWS, C_IFSWS);
104 setctypes("=-+?", C_SUBOP1);
105 setctypes("\t\n \"#$&'()*;<=>?[\\]`|", C_QUOTE);
108 /* called from XcheckN() to grow buffer */
110 Xcheck_grow(XString *xsp, const char *xp, size_t more)
112 const char *old_beg = xsp->beg;
116 /* (xsp->len + X_EXTRA) never overflows */
117 checkoktoadd(more, xsp->len + X_EXTRA);
118 xsp->beg = aresize(xsp->beg, (xsp->len += more) + X_EXTRA, xsp->areap);
119 xsp->end = xsp->beg + xsp->len;
120 return (xsp->beg + (xp - old_beg));
124 #define SHFLAGS_DEFNS
125 #define FN(sname,cname,flags,ochar) \
126 static const struct { \
127 /* character flag (if any) */ \
130 unsigned char optflags; \
131 /* long name of option */ \
132 char name[sizeof(sname)]; \
133 } shoptione_ ## cname = { \
134 ochar, flags, sname \
136 #include "sh_flags.gen"
138 #define OFC(i) (options[i][-2])
139 #define OFF(i) (((const unsigned char *)options[i])[-1])
140 #define OFN(i) (options[i])
142 const char * const options[] = {
143 #define SHFLAGS_ITEMS
144 #include "sh_flags.gen"
148 * translate -o option into F* constant (also used for test -o option)
151 option(const char *n)
155 if ((n[0] == '-' || n[0] == '+') && n[1] && !n[2])
156 while (i < NELEM(options)) {
162 while (i < NELEM(options)) {
163 if (!strcmp(OFN(i), n))
171 struct options_info {
173 int opts[NELEM(options)];
176 static void options_fmt_entry(char *, size_t, unsigned int, const void *);
177 static void printoptions(bool);
179 /* format a single select menu item */
181 options_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
183 const struct options_info *oi = (const struct options_info *)arg;
185 shf_snprintf(buf, buflen, "%-*s %s",
186 oi->opt_width, OFN(oi->opts[i]),
187 Flag(oi->opts[i]) ? "on" : "off");
191 printoptions(bool verbose)
196 size_t n = 0, len, octs = 0;
197 struct options_info oi;
198 struct columnise_opts co;
200 /* verbose version */
201 shf_puts("Current option settings\n", shl_stdout);
204 while (i < NELEM(options)) {
205 if ((len = strlen(OFN(i)))) {
209 len = utf_mbswidth(OFN(i));
210 if ((int)len > oi.opt_width)
211 oi.opt_width = (int)len;
217 co.prefcol = co.do_last = true;
218 print_columns(&co, n, options_fmt_entry, &oi,
219 octs + 4, oi.opt_width + 4);
221 /* short version like AT&T ksh93 */
222 shf_puts(Tset, shl_stdout);
223 while (i < NELEM(options)) {
224 if (Flag(i) && OFN(i)[0])
225 shprintf(" -o %s", OFN(i));
228 shf_putc('\n', shl_stdout);
236 char c, m[(int)FNFLAGS + 1];
239 while (i < NELEM(options)) {
240 if ((c = OFC(i)) && Flag(i))
244 strndupx(cp, m, cp - m, ATEMP);
248 /* change a Flag(*) value; takes care of special actions */
250 change_flag(enum sh_flag f, int what, bool newset)
252 unsigned char oldval;
253 unsigned char newval = (newset ? 1 : 0);
256 change_xtrace(newval, true);
260 Flag(f) = newval = (newset ? 1 : 0);
261 #ifndef MKSH_UNEMPLOYED
263 if (what != OF_CMDLINE && newval != oldval)
267 #ifndef MKSH_NO_CMDLINE_EDITING
272 f == FEMACS || f == FGMACS) && newval) {
276 Flag(FEMACS) = Flag(FGMACS) = 0;
280 if (f == FPRIVILEGED && oldval && !newval) {
281 /* Turning off -p? */
283 /*XXX this can probably be optimised */
284 kshegid = kshgid = getgid();
285 ksheuid = kshuid = getuid();
287 DO_SETUID(setresgid, (kshegid, kshegid, kshegid));
289 /* setgroups doesn't EAGAIN on Linux */
290 setgroups(1, &kshegid);
292 DO_SETUID(setresuid, (ksheuid, ksheuid, ksheuid));
293 #else /* !HAVE_SETRESUGID */
294 /* setgid, setegid, seteuid don't EAGAIN on Linux */
296 #ifndef MKSH__NO_SETEUGID
299 DO_SETUID(setuid, (ksheuid));
300 #ifndef MKSH__NO_SETEUGID
303 #endif /* !HAVE_SETRESUGID */
304 } else if ((f == FPOSIX || f == FSH) && newval) {
305 /* Turning on -o posix or -o sh? */
306 Flag(FBRACEEXPAND) = 0;
307 } else if (f == FTALKING) {
308 /* Changing interactive flag? */
309 if ((what == OF_CMDLINE || what == OF_SET) && procpid == kshpid)
310 Flag(FTALKING_I) = newval;
315 change_xtrace(unsigned char newval, bool dosnapshot)
317 static bool in_xtrace;
322 if (!dosnapshot && newval == Flag(FXTRACE))
325 if (Flag(FXTRACE) == 2) {
326 shf_putc('\n', shl_xtrace);
328 shf_flush(shl_xtrace);
331 if (!dosnapshot && Flag(FXTRACE) == 1)
339 shf_flush(shl_xtrace);
340 if (shl_xtrace->fd != 2)
341 close(shl_xtrace->fd);
342 if (!newval || (shl_xtrace->fd = savefd(2)) == -1)
346 if ((Flag(FXTRACE) = newval) == 2) {
349 shf_puts(substitute(str_val(global("PS4")), 0), shl_xtrace);
356 * Parse command line and set command arguments. Returns the index of
357 * non-option arguments, -1 if there is an error.
360 parse_args(const char **argv,
361 /* OF_FIRSTTIME, OF_CMDLINE, or OF_SET */
365 static const char cmd_opts[] =
366 #define SHFLAGS_NOT_SET
367 #define SHFLAGS_OPTCS
368 #include "sh_flags.gen"
369 #undef SHFLAGS_NOT_SET
371 static const char set_opts[] =
372 #define SHFLAGS_NOT_CMD
373 #define SHFLAGS_OPTCS
374 #include "sh_flags.gen"
375 #undef SHFLAGS_NOT_CMD
379 const char *array = NULL;
382 int optc, arrayset = 0;
383 bool sortargs = false;
384 bool fcompatseen = false;
386 if (what == OF_CMDLINE) {
387 const char *p = argv[0], *q;
389 * Set FLOGIN before parsing options so user can clear
394 if (mksh_cdirsep(*q++))
396 Flag(FLOGIN) = (*p == '-');
398 } else if (what == OF_FIRSTTIME) {
402 ksh_getopt_reset(&go, GF_ERROR|GF_PLUSOPT);
403 while ((optc = ksh_getopt(argv, &go, opts)) != -1) {
404 set = tobool(!(go.info & GI_PLUS));
407 if (what == OF_FIRSTTIME)
409 arrayset = set ? 1 : -1;
414 if (what == OF_FIRSTTIME)
416 if (go.optarg == NULL) {
418 * lone -o: print options
420 * Note that on the command line, -o requires
421 * an option (ie, can't get here if what is
427 i = option(go.optarg);
428 if ((i == FPOSIX || i == FSH) && set && !fcompatseen) {
430 * If running 'set -o posix' or
431 * 'set -o sh', turn off the other;
432 * if running 'set -o posix -o sh'
433 * allow both to be set though.
439 if ((i != (size_t)-1) && (set ? 1U : 0U) == Flag(i))
441 * Don't check the context if the flag
442 * isn't changing - makes "set -o interactive"
443 * work if you're already interactive. Needed
444 * if the output of "set +o" is to be used.
447 else if ((i != (size_t)-1) && (OFF(i) & what))
448 change_flag((enum sh_flag)i, what, set);
450 bi_errorf(Tf_sD_s, go.optarg,
458 if (what != OF_FIRSTTIME)
460 #ifndef KSH_CHVT_CODE
461 errorf("no TIOCSCTTY ioctl");
463 change_flag(FTALKING, OF_CMDLINE, true);
473 if (what == OF_FIRSTTIME)
475 /* -s: sort positional params (AT&T ksh stupidity) */
476 if (what == OF_SET && optc == 's') {
480 for (i = 0; i < NELEM(options); i++)
481 if (optc == OFC(i) &&
483 change_flag((enum sh_flag)i, what, set);
486 if (i == NELEM(options))
487 internal_errorf("parse_args: '%c'", optc);
490 if (!(go.info & GI_MINUSMINUS) && argv[go.optind] &&
491 (argv[go.optind][0] == '-' || argv[go.optind][0] == '+') &&
492 argv[go.optind][1] == '\0') {
493 /* lone - clears -v and -x flags */
494 if (argv[go.optind][0] == '-') {
496 change_xtrace(0, false);
498 /* set skips lone - or + option */
502 /* -- means set $#/$* even if there are no arguments */
503 *setargsp = !arrayset && ((go.info & GI_MINUSMINUS) ||
507 const char *ccp = NULL;
510 ccp = skip_varname(array, false);
511 if (!ccp || !(!ccp[0] || (ccp[0] == '+' && !ccp[1]))) {
512 bi_errorf(Tf_sD_s, array, Tnot_ident);
517 for (i = go.optind; argv[i]; i++)
519 qsort(&argv[go.optind], i - go.optind, sizeof(void *),
523 go.optind += set_array(array, tobool(arrayset > 0),
529 /* parse a decimal number: returns 0 if string isn't a number, 1 otherwise */
531 getn(const char *s, int *ai)
541 } while (ksh_isspace(c));
556 if (num.u > 214748364U)
557 /* overflow on multiplication */
559 num.u = num.u * 10U + (unsigned int)ksh_numdig(c);
560 /* now: num.u <= 2147483649U */
561 } while ((c = *s++));
563 if (num.u > (neg ? 2147483648U : 2147483647U))
564 /* overflow for signed 32-bit int */
574 * pattern simplifications:
575 * - @(x) -> x (not @(x|y) though)
579 simplify_gmatch_pattern(const unsigned char *sp)
582 unsigned char *cp, *dp;
583 const unsigned char *ps, *se;
585 cp = alloc(strlen((const void *)sp) + 1, ATEMP);
586 goto simplify_gmatch_pat1a;
588 /* foo@(b@(a)r)b@(a|a)z -> foobarb@(a|a)z */
589 simplify_gmatch_pat1:
591 simplify_gmatch_pat1a:
593 se = sp + strlen((const void *)sp);
594 while ((c = *sp++)) {
599 switch ((c = *sp++)) {
603 /* check whether it has only one clause */
604 ps = pat_scan(sp, se, true);
605 if (!ps || ps[-1] != /*(*/ ')')
608 /* copy inner clause until matching close */
610 while ((const unsigned char *)sp < ps)
612 /* skip MAGIC and closing parenthesis */
614 /* copy the rest of the pattern */
615 memmove(dp, sp, strlen((const void *)sp) + 1);
616 /* redo from start */
617 goto simplify_gmatch_pat1;
624 /* collapse adjacent asterisk wildcards */
626 while ((c = *sp++)) {
631 switch ((c = *sp++)) {
633 while (ISMAGIC(sp[0]) && sp[1] == c)
642 /* return the result, allocated from ATEMP */
646 /* -------- gmatch.c -------- */
649 * int gmatch(string, pattern)
650 * char *string, *pattern;
652 * Match a pattern as in sh(1).
653 * pattern character are prefixed with MAGIC by expand.
656 gmatchx(const char *s, const char *p, bool isfile)
662 if (s == NULL || p == NULL)
668 * isfile is false iff no syntax check has been done on
669 * the pattern. If check fails, just to a strcmp().
671 if (!isfile && !has_globbing(p, pe)) {
672 size_t len = pe - p + 1;
674 char *t = len <= sizeof(tbuf) ? tbuf : alloc(len, ATEMP);
676 return (!strcmp(t, s));
680 * since the do_gmatch() engine sucks so much, we must do some
681 * pattern simplifications
683 pnew = simplify_gmatch_pattern((const unsigned char *)p);
684 pe = pnew + strlen(pnew);
686 rv = do_gmatch((const unsigned char *)s, (const unsigned char *)se,
687 (const unsigned char *)pnew, (const unsigned char *)pe);
693 * Returns if p is a syntacticly correct globbing pattern, false
694 * if it contains no pattern characters or if there is a syntax error.
696 * - [ with no closing ]
697 * - imbalanced $(...) expression
698 * - [...] and *(...) not nested (eg, [a$(b|]c), *(a[b|c]d))
702 * if dest given, copy to dst
704 * - if magic && (no globbing || syntax error)
710 has_globbing(const char *xp, const char *xpe)
712 const unsigned char *p = (const unsigned char *) xp;
713 const unsigned char *pe = (const unsigned char *) xpe;
715 int nest = 0, bnest = 0;
716 bool saw_glob = false;
718 bool in_bracket = false;
720 for (; p < pe; p++) {
723 if ((c = *++p) == '*' || c == '?')
729 if (ISMAGIC(p[1]) && p[2] == '!')
731 if (ISMAGIC(p[1]) && p[2] == ']')
734 /*XXX Do we need to check ranges here? POSIX Q */
735 } else if (c == ']') {
742 } else if ((c & 0x80) && vstrchr("*+?@! ", c & 0x7f)) {
748 } else if (c == '|') {
749 if (in_bracket && !bnest)
752 } else if (c == /*(*/ ')') {
761 * else must be a MAGIC-MAGIC, or MAGIC-!,
762 * MAGIC--, MAGIC-], MAGIC-{, MAGIC-, MAGIC-}
765 return (saw_glob && !in_bracket && !nest);
768 /* Function must return either 0 or 1 (assumed by code for 0x80|'!') */
770 do_gmatch(const unsigned char *s, const unsigned char *se,
771 const unsigned char *p, const unsigned char *pe)
773 unsigned char sc, pc;
774 const unsigned char *prest, *psub, *pnext;
775 const unsigned char *srest;
777 if (s == NULL || p == NULL)
781 sc = s < se ? *s : '\0';
790 if (sc == 0 || (p = gmatch_cclass(p, sc)) == NULL)
799 s += utf_ptradj((const void *)s);
808 if (do_gmatch(s, se, p, pe))
814 * [*+?@!](pattern|pattern|..)
815 * This is also needed for ${..%..}, etc.
818 /* matches one or more times */
820 /* matches zero or more times */
822 if (!(prest = pat_scan(p, pe, false)))
825 /* take care of zero matches */
826 if (p[-1] == (0x80 | '*') &&
827 do_gmatch(s, se, prest, pe))
829 for (psub = p; ; psub = pnext) {
830 pnext = pat_scan(psub, pe, true);
831 for (srest = s; srest <= se; srest++) {
832 if (do_gmatch(s, srest, psub, pnext - 2) &&
833 (do_gmatch(srest, se, prest, pe) ||
834 (s != srest && do_gmatch(srest,
843 /* matches zero or once */
845 /* matches one of the patterns */
849 if (!(prest = pat_scan(p, pe, false)))
852 /* Take care of zero matches */
853 if (p[-1] == (0x80 | '?') &&
854 do_gmatch(s, se, prest, pe))
856 for (psub = p; ; psub = pnext) {
857 pnext = pat_scan(psub, pe, true);
858 srest = prest == pe ? se : s;
859 for (; srest <= se; srest++) {
860 if (do_gmatch(s, srest, psub, pnext - 2) &&
861 do_gmatch(srest, se, prest, pe))
869 /* matches none of the patterns */
871 if (!(prest = pat_scan(p, pe, false)))
874 for (srest = s; srest <= se; srest++) {
877 for (psub = p; ; psub = pnext) {
878 pnext = pat_scan(psub, pe, true);
879 if (do_gmatch(s, srest, psub,
888 do_gmatch(srest, se, prest, pe))
902 static const unsigned char *
903 gmatch_cclass(const unsigned char *p, unsigned char sub)
906 bool notp, found = false;
907 const unsigned char *orig_p = p;
909 if ((notp = tobool(ISMAGIC(*p) && *++p == '!')))
915 if ((c & 0x80) && !ISMAGIC(c)) {
916 /* extended pattern matching: *+?@! */
918 /* XXX the ( char isn't handled as part of [] */
920 /* simile for @: plain (..) */
925 /* No closing ] - act as if the opening [ was quoted */
926 return (sub == '[' ? orig_p : NULL);
927 if (ISMAGIC(p[0]) && p[1] == '-' &&
928 (!ISMAGIC(p[2]) || p[3] != ']')) {
934 if ((d & 0x80) && !ISMAGIC(d))
937 /* POSIX says this is an invalid expression */
942 if (c == sub || (c <= sub && sub <= d))
944 } while (!(ISMAGIC(p[0]) && p[1] == ']'));
946 return ((found != notp) ? p+2 : NULL);
949 /* Look for next ) or | (if match_sep) in *(foo|bar) pattern */
950 static const unsigned char *
951 pat_scan(const unsigned char *p, const unsigned char *pe, bool match_sep)
955 for (; p < pe; p++) {
958 if ((*++p == /*(*/ ')' && nest-- == 0) ||
959 (*p == '|' && match_sep && nest == 0))
961 if ((*p & 0x80) && vstrchr("*+?@! ", *p & 0x7f))
968 xstrcmp(const void *p1, const void *p2)
970 return (strcmp(*(const char * const *)p1, *(const char * const *)p2));
973 /* Initialise a Getopt structure */
975 ksh_getopt_reset(Getopt *go, int flags)
987 * getopt() used for shell built-in commands, the getopts command, and
988 * command line options.
989 * A leading ':' in options means don't print errors, instead return '?'
990 * or ':' and set go->optarg to the offending option character.
991 * If GF_ERROR is set (and option doesn't start with :), errors result in
992 * a call to bi_errorf().
994 * Non-standard features:
995 * - ';' is like ':' in options, except the argument is optional
996 * (if it isn't present, optarg is set to 0).
998 * - ',' is like ':' in options, except the argument always immediately
999 * follows the option character (optarg is set to the null string if
1000 * the option is missing).
1001 * Used for 'read -u2', 'print -u2' and fc -40.
1002 * - '#' is like ':' in options, expect that the argument is optional
1003 * and must start with a digit. If the argument doesn't start with a
1004 * digit, it is assumed to be missing and normal option processing
1005 * continues (optarg is set to 0 if the option is missing).
1006 * Used for 'typeset -LZ4'.
1007 * - accepts +c as well as -c IF the GF_PLUSOPT flag is present. If an
1008 * option starting with + is accepted, the GI_PLUS flag will be set
1012 ksh_getopt(const char **argv, Getopt *go, const char *optionsp)
1017 if (go->p == 0 || (c = argv[go->optind - 1][go->p]) == '\0') {
1018 const char *arg = argv[go->optind], flag = arg ? *arg : '\0';
1021 if (flag == '-' && ksh_isdash(arg + 1)) {
1024 go->info |= GI_MINUSMINUS;
1029 /* neither a - nor a + (if + allowed) */
1030 (!(go->flags & GF_PLUSOPT) || flag != '+')) ||
1031 (c = arg[1]) == '\0') {
1036 go->info &= ~(GI_MINUS|GI_PLUS);
1037 go->info |= flag == '-' ? GI_MINUS : GI_PLUS;
1040 if (c == '?' || c == ':' || c == ';' || c == ',' || c == '#' ||
1041 !(o = cstrchr(optionsp, c))) {
1042 if (optionsp[0] == ':') {
1044 go->optarg = go->buf;
1046 warningf(true, Tf_optfoo,
1047 (go->flags & GF_NONAME) ? "" : argv[0],
1048 (go->flags & GF_NONAME) ? "" : Tcolsp,
1049 c, Tunknown_option);
1050 if (go->flags & GF_ERROR)
1056 * : means argument must be present, may be part of option argument
1057 * or the next argument
1058 * ; same as : but argument may be missing
1059 * , means argument is part of option argument, and may be null.
1061 if (*++o == ':' || *o == ';') {
1062 if (argv[go->optind - 1][go->p])
1063 go->optarg = argv[go->optind - 1] + go->p;
1064 else if (argv[go->optind])
1065 go->optarg = argv[go->optind++];
1069 if (optionsp[0] == ':') {
1071 go->optarg = go->buf;
1074 warningf(true, Tf_optfoo,
1075 (go->flags & GF_NONAME) ? "" : argv[0],
1076 (go->flags & GF_NONAME) ? "" : Tcolsp,
1078 if (go->flags & GF_ERROR)
1083 } else if (*o == ',') {
1084 /* argument is attached to option character, even if null */
1085 go->optarg = argv[go->optind - 1] + go->p;
1087 } else if (*o == '#') {
1089 * argument is optional and may be attached or unattached
1090 * but must start with a digit. optarg is set to 0 if the
1091 * argument is missing.
1093 if (argv[go->optind - 1][go->p]) {
1094 if (ksh_isdigit(argv[go->optind - 1][go->p])) {
1095 go->optarg = argv[go->optind - 1] + go->p;
1100 if (argv[go->optind] && ksh_isdigit(argv[go->optind][0])) {
1101 go->optarg = argv[go->optind++];
1111 * print variable/alias value using necessary quotes
1112 * (POSIX says they should be suitable for re-entry...)
1113 * No trailing newline is printed.
1116 print_value_quoted(struct shf *shf, const char *s)
1119 const unsigned char *p = (const unsigned char *)s;
1120 bool inquote = true;
1122 /* first, check whether any quotes are needed */
1123 while ((c = *p++) >= 32)
1124 if (ctype(c, C_QUOTE))
1127 p = (const unsigned char *)s;
1130 /* nope, use the shortcut */
1135 /* otherwise, quote nicely via state machine */
1136 while ((c = *p++) != 0) {
1139 * multiple single quotes or any of them
1140 * at the beginning of a string look nicer
1141 * this way than when simply substituting
1144 shf_putc('\'', shf);
1147 shf_putc('\\', shf);
1148 } else if (!inquote) {
1149 shf_putc('\'', shf);
1158 /* use $'...' quote format */
1160 shf_putc('\'', shf);
1161 while ((c = *p) != 0) {
1163 n = utf_mbtowc(&wc, (const char *)p);
1164 if (n != (size_t)-1) {
1166 shf_fprintf(shf, "\\u%04X", wc);
1172 /* see unbksl() in this file for comments */
1202 /* take E not e because \e is \ in *roff */
1206 shf_putc('\\', shf);
1211 if (c < 32 || c > 0x7E) {
1214 shf_fprintf(shf, "\\%03o", c);
1225 shf_putc('\'', shf);
1229 * Print things in columns and rows - func() is called to format
1233 print_columns(struct columnise_opts *opts, unsigned int n,
1234 void (*func)(char *, size_t, unsigned int, const void *),
1235 const void *arg, size_t max_oct, size_t max_colz)
1237 unsigned int i, r = 0, c, rows, cols, nspace, max_col;
1243 if (max_colz > 2147483646) {
1245 internal_warningf("print_columns called with %s=%zu >= INT_MAX",
1246 "max_col", max_colz);
1250 max_col = (unsigned int)max_colz;
1252 if (max_oct > 2147483646) {
1254 internal_warningf("print_columns called with %s=%zu >= INT_MAX",
1255 "max_oct", max_oct);
1260 str = alloc(max_oct, ATEMP);
1263 * We use (max_col + 2) to consider the separator space.
1264 * Note that no spaces are printed after the last column
1265 * to avoid problems with terminals that have auto-wrap,
1266 * but we need to also take this into account in x_cols.
1268 cols = (x_cols + 1) / (max_col + 2);
1270 /* if we can only print one column anyway, skip the goo */
1274 shf_putc(opts->linesep, opts->shf);
1276 (*func)(str, max_oct, r++, arg);
1277 shf_puts(str, opts->shf);
1282 rows = (n + cols - 1) / cols;
1283 if (opts->prefcol && cols > rows) {
1285 rows = (n + cols - 1) / cols;
1288 nspace = (x_cols - max_col * cols) / cols;
1294 shf_putchar(opts->linesep, opts->shf);
1296 for (c = 0; c < cols; c++) {
1297 if ((i = c * rows + r) >= n)
1299 (*func)(str, max_oct, i, arg);
1301 shf_puts(str, opts->shf);
1303 shf_fprintf(opts->shf, "%*s%*s",
1304 (int)max_col, str, (int)nspace, null);
1310 shf_putchar(opts->linesep, opts->shf);
1314 /* strip all NUL bytes from buf; output is NUL-terminated if stripped */
1316 strip_nuls(char *buf, size_t len)
1320 if (!len || !(dp = memchr(buf, '\0', len)))
1327 while (cp++ < ep && *cp == '\0')
1329 while (cp < ep && *cp != '\0')
1332 goto cp_has_nul_byte;
1338 * Like read(2), but if read fails due to non-blocking flag,
1339 * resets flag and restarts read.
1342 blocking_read(int fd, char *buf, size_t nbytes)
1345 bool tried_reset = false;
1347 while ((ret = read(fd, buf, nbytes)) < 0) {
1348 if (!tried_reset && errno == EAGAIN) {
1349 if (reset_nonblock(fd) > 0) {
1361 * Reset the non-blocking flag on the specified file descriptor.
1362 * Returns -1 if there was an error, 0 if non-blocking wasn't set,
1366 reset_nonblock(int fd)
1370 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1372 if (!(flags & O_NONBLOCK))
1374 flags &= ~O_NONBLOCK;
1375 if (fcntl(fd, F_SETFL, flags) < 0)
1380 /* getcwd(3) equivalent, allocates from ATEMP but doesn't resize */
1384 #ifdef MKSH__NO_PATH_MAX
1387 if ((cp = get_current_dir_name())) {
1388 strdupx(rv, cp, ATEMP);
1395 if (!getcwd((rv = alloc(PATH_MAX + 1, ATEMP)), PATH_MAX)) {
1409 do_realpath(const char *upath)
1411 char *xp, *ip, *tp, *ipath, *ldest = NULL;
1416 #ifdef MKSH__NO_PATH_MAX
1417 size_t ldestlen = 0;
1418 #define pathlen sb.st_size
1419 #define pathcnd (ldestlen < (pathlen + 1))
1421 #define pathlen PATH_MAX
1422 #define pathcnd (!ldest)
1424 /* max. recursion depth */
1427 if (mksh_abspath(upath)) {
1428 /* upath is an absolute pathname */
1429 strdupx(ipath, upath, ATEMP);
1431 /* upath is a relative pathname, prepend cwd */
1432 if ((tp = ksh_get_wd()) == NULL || !mksh_abspath(tp))
1434 ipath = shf_smprintf(Tf_sss, tp, "/", upath);
1438 /* ipath and upath are in memory at the same time -> unchecked */
1439 Xinit(xs, xp, strlen(ip = ipath) + 1, ATEMP);
1441 /* now jump into the deep of the loop */
1442 goto beginning_of_a_pathname;
1445 /* skip slashes in input */
1446 while (mksh_cdirsep(*ip))
1451 /* get next pathname component from input */
1453 while (*ip && !mksh_cdirsep(*ip))
1457 /* check input for "." and ".." */
1460 /* just continue with the next one */
1462 else if (len == 2 && tp[1] == '.') {
1463 /* strip off last pathname component */
1464 while (xp > Xstring(xs, xp))
1465 if (mksh_cdirsep(*--xp))
1467 /* then continue with the next one */
1472 /* store output position away, then append slash to output */
1473 pos = Xsavepos(xs, xp);
1474 /* 1 for the '/' and len + 1 for tp and the NUL from below */
1475 XcheckN(xs, xp, 1 + len + 1);
1478 /* append next pathname component to output */
1479 memcpy(xp, tp, len);
1483 /* lstat the current output, see if it's a symlink */
1484 if (mksh_lstat(Xstring(xs, xp), &sb)) {
1486 if (errno == ENOENT) {
1487 /* because the pathname does not exist */
1488 while (mksh_cdirsep(*ip))
1489 /* skip any trailing slashes */
1491 /* no more components left? */
1493 /* we can still return successfully */
1495 /* more components left? fall through */
1497 /* not ENOENT or not at the end of ipath */
1501 /* check if we encountered a symlink? */
1502 if (S_ISLNK(sb.st_mode)) {
1503 #ifndef MKSH__NO_SYMLINK
1504 /* reached maximum recursion depth? */
1506 /* yep, prevent infinite loops */
1511 /* get symlink(7) target */
1513 #ifdef MKSH__NO_PATH_MAX
1514 if (notoktoadd(pathlen, 1)) {
1515 errno = ENAMETOOLONG;
1519 ldest = aresize(ldest, pathlen + 1, ATEMP);
1521 llen = readlink(Xstring(xs, xp), ldest, pathlen);
1528 * restart if symlink target is an absolute path,
1529 * otherwise continue with currently resolved prefix
1531 /* append rest of current input path to link target */
1532 tp = shf_smprintf(Tf_sss, ldest, *ip ? "/" : "", ip);
1533 afree(ipath, ATEMP);
1535 if (!mksh_abspath(ldest)) {
1536 /* symlink target is a relative path */
1537 xp = Xrestpos(xs, xp, pos);
1541 /* symlink target is an absolute path */
1542 xp = Xstring(xs, xp);
1543 beginning_of_a_pathname:
1544 /* assert: (ip == ipath)[0] == '/' */
1545 /* assert: xp == xs.beg => start of path */
1547 /* exactly two leading slashes? (SUSv4 3.266) */
1548 /* @komh do NOT use mksh_cdirsep() here */
1549 if (ip[1] == '/' && ip[2] != '/') {
1550 /* keep them, e.g. for UNC pathnames */
1555 /* otherwise (no symlink) merely go on */
1559 * either found the target and successfully resolved it,
1560 * or found its parent directory and may create it
1562 if (Xlength(xs, xp) == 0)
1564 * if the resolved pathname is "", make it "/",
1565 * otherwise do not add a trailing slash
1571 * if source path had a trailing slash, check if target path
1572 * is not a non-directory existing file
1574 if (ip > ipath && mksh_cdirsep(ip[-1])) {
1575 if (stat(Xstring(xs, xp), &sb)) {
1576 if (errno != ENOENT)
1578 } else if (!S_ISDIR(sb.st_mode)) {
1582 /* target now either does not exist or is a directory */
1585 /* return target path */
1586 afree(ldest, ATEMP);
1587 afree(ipath, ATEMP);
1588 return (Xclose(xs, xp));
1591 /* save; freeing memory might trash it */
1593 afree(ldest, ATEMP);
1594 afree(ipath, ATEMP);
1604 * Makes a filename into result using the following algorithm.
1605 * - make result NULL
1606 * - if file starts with '/', append file to result & set cdpathp to NULL
1607 * - if file starts with ./ or ../ append cwd and file to result
1608 * and set cdpathp to NULL
1609 * - if the first element of cdpathp doesnt start with a '/' xx or '.' xx
1610 * then cwd is appended to result.
1611 * - the first element of cdpathp is appended to result
1612 * - file is appended to result
1613 * - cdpathp is set to the start of the next element in cdpathp (or NULL
1614 * if there are no more elements.
1615 * The return value indicates whether a non-null element from cdpathp
1616 * was appended to result.
1619 make_path(const char *cwd, const char *file,
1620 /* pointer to colon-separated list */
1626 bool use_cdpath = true;
1628 size_t len, plen = 0;
1629 char *xp = Xstring(*xsp, xp);
1634 if (mksh_abspath(file)) {
1638 if (file[0] == '.') {
1643 if (mksh_cdirsep(c) || c == '\0')
1650 else if (use_cdpath) {
1653 while (*pend && *pend != MKSH_PATHSEPC)
1655 plen = pend - plist;
1656 *cdpathp = *pend ? pend + 1 : NULL;
1659 if ((!use_cdpath || !plen || !mksh_abspath(plist)) &&
1662 XcheckN(*xsp, xp, len);
1663 memcpy(xp, cwd, len);
1665 if (!mksh_cdirsep(cwd[len - 1]))
1666 Xput(*xsp, xp, '/');
1668 *phys_pathp = Xlength(*xsp, xp);
1669 if (use_cdpath && plen) {
1670 XcheckN(*xsp, xp, plen);
1671 memcpy(xp, plist, plen);
1673 if (!mksh_cdirsep(plist[plen - 1]))
1674 Xput(*xsp, xp, '/');
1679 len = strlen(file) + 1;
1680 XcheckN(*xsp, xp, len);
1681 memcpy(xp, file, len);
1690 * Simplify pathnames containing "." and ".." entries.
1692 * simplify_path(this) = that
1693 * /a/b/c/./../d/.. /a/b
1694 * //./C/foo/bar/../baz //C/foo/baz
1696 * /foo/../../bar /bar
1697 * /foo/./blah/.. /foo
1701 * foo/../../../bar ../../bar
1704 simplify_path(char *p)
1706 char *dp, *ip, *sp, *tp;
1714 /* exactly two leading slashes? (SUSv4 3.266) */
1715 /* @komh no mksh_cdirsep() here! */
1716 if (p[1] == '/' && p[2] != '/')
1717 /* keep them, e.g. for UNC pathnames */
1731 /* skip slashes in input */
1732 while (mksh_cdirsep(*ip))
1737 /* get next pathname component from input */
1739 while (*ip && !mksh_cdirsep(*ip))
1743 /* check input for "." and ".." */
1746 /* just continue with the next one */
1748 else if (len == 2 && tp[1] == '.') {
1749 /* parent level, but how? */
1750 if (mksh_abspath(p))
1751 /* absolute path, only one way */
1752 goto strip_last_component;
1754 /* relative path, with subpaths */
1756 strip_last_component:
1757 /* strip off last pathname component */
1759 if (mksh_cdirsep(*--dp))
1762 /* relative path, at its beginning */
1764 /* or already dotdot-slash'd */
1766 /* keep dotdot-slash if not absolute */
1772 /* then continue with the next one */
1780 /* append next pathname component to output */
1781 memmove(dp, tp, len);
1784 /* append slash if we continue */
1786 /* try next component */
1789 /* empty path -> dot */
1790 *dp++ = needslash ? '/' : '.';
1795 set_current_wd(const char *nwd)
1797 char *allocd = NULL;
1800 allocd = ksh_get_wd();
1801 nwd = allocd ? allocd : null;
1804 afree(current_wd, APERM);
1805 strdupx(current_wd, nwd, APERM);
1807 afree(allocd, ATEMP);
1811 c_cd(const char **wp)
1813 int optc, rv, phys_path;
1814 bool physical = tobool(Flag(FPHYSICAL));
1815 /* was a node from cdpath added in? */
1817 /* show where we went?, error for $PWD */
1818 bool printpath = false, eflag = false;
1819 struct tbl *pwd_s, *oldpwd_s;
1821 char *dir, *allocd = NULL, *tryp, *pwd, *cdpath;
1823 while ((optc = ksh_getopt(wp, &builtin_opt, "eLP")) != -1)
1837 wp += builtin_opt.optind;
1839 if (Flag(FRESTRICTED)) {
1840 bi_errorf(Tcant_cd);
1844 pwd_s = global(TPWD);
1845 oldpwd_s = global(TOLDPWD);
1848 /* No arguments - go home */
1849 if ((dir = str_val(global("HOME"))) == null) {
1850 bi_errorf("no home directory (HOME not set)");
1853 } else if (!wp[1]) {
1854 /* One argument: - or dir */
1855 strdupx(allocd, wp[0], ATEMP);
1856 if (ksh_isdash((dir = allocd))) {
1857 afree(allocd, ATEMP);
1859 dir = str_val(oldpwd_s);
1861 bi_errorf(Tno_OLDPWD);
1866 } else if (!wp[2]) {
1867 /* Two arguments - substitute arg1 in PWD for arg2 */
1868 size_t ilen, olen, nlen, elen;
1871 if (!current_wd[0]) {
1872 bi_errorf("can't determine current directory");
1876 * substitute arg1 for arg2 in current path.
1877 * if the first substitution fails because the cd fails
1878 * we could try to find another substitution. For now
1881 if ((cp = strstr(current_wd, wp[0])) == NULL) {
1882 bi_errorf(Tbadsubst);
1886 * ilen = part of current_wd before wp[0]
1887 * elen = part of current_wd after wp[0]
1888 * because current_wd and wp[1] need to be in memory at the
1889 * same time beforehand the addition can stay unchecked
1891 ilen = cp - current_wd;
1892 olen = strlen(wp[0]);
1893 nlen = strlen(wp[1]);
1894 elen = strlen(current_wd + ilen + olen) + 1;
1895 dir = allocd = alloc(ilen + nlen + elen, ATEMP);
1896 memcpy(dir, current_wd, ilen);
1897 memcpy(dir + ilen, wp[1], nlen);
1898 memcpy(dir + ilen + nlen, current_wd + ilen + olen, elen);
1901 bi_errorf(Ttoo_many_args);
1905 #ifdef MKSH__NO_PATH_MAX
1906 /* only a first guess; make_path will enlarge xs if necessary */
1907 XinitN(xs, 1024, ATEMP);
1909 XinitN(xs, PATH_MAX, ATEMP);
1912 cdpath = str_val(global("CDPATH"));
1914 cdnode = make_path(current_wd, dir, &cdpath, &xs, &phys_path);
1916 rv = chdir(tryp = Xstring(xs, xp) + phys_path);
1918 simplify_path(Xstring(xs, xp));
1919 rv = chdir(tryp = Xstring(xs, xp));
1921 } while (rv < 0 && cdpath != NULL);
1925 bi_errorf(Tf_sD_s, dir, "bad directory");
1927 bi_errorf(Tf_sD_s, tryp, cstrerror(errno));
1928 afree(allocd, ATEMP);
1935 /* allocd (above) => dir, which is no longer used */
1936 afree(allocd, ATEMP);
1939 /* Clear out tracked aliases with relative paths */
1943 * Set OLDPWD (note: unsetting OLDPWD does not disable this
1944 * setting in AT&T ksh)
1947 /* Ignore failure (happens if readonly or integer) */
1948 setstr(oldpwd_s, current_wd, KSH_RETURN_ERROR);
1950 if (!mksh_abspath(Xstring(xs, xp))) {
1952 } else if (!physical) {
1953 goto norealpath_PWD;
1954 } else if ((pwd = allocd = do_realpath(Xstring(xs, xp))) == NULL) {
1958 pwd = Xstring(xs, xp);
1965 set_current_wd(ptmp);
1966 /* Ignore failure (happens if readonly or integer) */
1967 setstr(pwd_s, ptmp, KSH_RETURN_ERROR);
1969 set_current_wd(null);
1970 pwd = Xstring(xs, xp);
1971 /* XXX unset $PWD? */
1975 if (printpath || cdnode)
1976 shprintf(Tf_sN, pwd);
1978 afree(allocd, ATEMP);
1984 #ifdef KSH_CHVT_CODE
1985 extern void chvt_reinit(void);
1988 chvt(const Getopt *go)
1990 const char *dv = go->optarg;
2004 if (stat(dv, &sb)) {
2005 cp = shf_smprintf("/dev/ttyC%s", dv);
2007 if (stat(dv, &sb)) {
2008 memmove(cp + 1, cp, /* /dev/tty */ 8);
2010 if (stat(dv, &sb)) {
2011 errorf(Tf_sD_sD_s, "chvt",
2012 "can't find tty", go->optarg);
2016 if (!(sb.st_mode & S_IFCHR))
2017 errorf(Tf_sD_sD_s, "chvt", "not a char device", dv);
2018 #ifndef MKSH_DISABLE_REVOKE_WARNING
2022 warningf(false, Tf_sD_s_s, "chvt",
2023 "new shell is potentially insecure, can't revoke",
2028 if ((fd = binopen2(dv, O_RDWR)) < 0) {
2030 if ((fd = binopen2(dv, O_RDWR)) < 0) {
2031 errorf(Tf_sD_s_s, "chvt", Tcant_open, dv);
2034 if (go->optarg[0] != '!') {
2037 errorf(Tf_sD_s_s, "chvt", "fork", "failed");
2045 errorf(Tf_sD_s_s, "chvt", "setsid", "failed");
2046 if (go->optarg[0] != '-') {
2047 if (ioctl(fd, TIOCSCTTY, NULL) == -1)
2048 errorf(Tf_sD_s_s, "chvt", "TIOCSCTTY", "failed");
2049 if (tcflush(fd, TCIOFLUSH))
2050 errorf(Tf_sD_s_s, "chvt", "TCIOFLUSH", "failed");
2052 ksh_dup2(fd, 0, false);
2053 ksh_dup2(fd, 1, false);
2054 ksh_dup2(fd, 2, false);
2057 rndset((unsigned long)chvt_rndsetup(go, sizeof(Getopt)));
2064 strchr(char *p, int ch)
2076 strstr(char *b, const char *l)
2081 if ((first = *l++) == '\0')
2085 while ((c = *b++) != first)
2088 if (strncmp(b, l, n))
2094 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
2096 strndup_i(const char *src, size_t len, Area *ap)
2101 dst = alloc(len + 1, ap);
2102 memcpy(dst, src, len);
2109 strdup_i(const char *src, Area *ap)
2111 return (src == NULL ? NULL : strndup_i(src, strlen(src), ap));
2116 #define INVTCK(r,t) do { \
2117 r.tv_usec = ((t) % (1000000 / CLK_TCK)) * (1000000 / CLK_TCK); \
2118 r.tv_sec = (t) / CLK_TCK; \
2119 } while (/* CONSTCOND */ 0)
2122 getrusage(int what, struct rusage *ru)
2127 if (/* ru == NULL || */ times(&tms) == (clock_t)-1)
2135 case RUSAGE_CHILDREN:
2143 INVTCK(ru->ru_utime, u);
2144 INVTCK(ru->ru_stime, s);
2150 * process the string available via fg (get a char)
2151 * and fp (put back a char) for backslash escapes,
2152 * assuming the first call to *fg gets the char di-
2153 * rectly after the backslash; return the character
2154 * (0..0xFF), Unicode (wc + 0x100), or -1 if no known
2155 * escape sequence was found
2158 unbksl(bool cstyle, int (*fg)(void), void (*fp)(int))
2166 * according to the comments in pdksh, \007 seems
2167 * to be more portable than \a (due to HP-UX cc,
2168 * Ultrix cc, old pcc, etc.) so we avoid the escape
2169 * sequence altogether in mksh and assume ASCII
2178 goto unknown_escape;
2199 /* assume ASCII here as well */
2210 goto unknown_escape;
2216 * look for an octal number with up to three
2217 * digits, not counting the leading zero;
2218 * convert it to a raw octet
2223 if ((c = (*fg)()) >= ord('0') && c <= ord('7'))
2224 wc = (wc << 3) + ksh_numdig(c);
2232 if (/* CONSTCOND */ 0)
2236 if (/* CONSTCOND */ 0)
2239 i = cstyle ? -1 : 2;
2241 * x: look for a hexadecimal number with up to
2242 * two (C style: arbitrary) digits; convert
2243 * to raw octet (C style: Unicode if >0xFF)
2244 * u/U: look for a hexadecimal number with up to
2245 * four (U: eight) digits; convert to Unicode
2250 if ((c = (*fg)()) >= ord('0') && c <= ord('9'))
2251 wc += ksh_numdig(c);
2252 else if (c >= ord('A') && c <= ord('F'))
2253 wc += ksh_numuc(c) + 10;
2254 else if (c >= ord('a') && c <= ord('f'))
2255 wc += ksh_numlc(c) + 10;
2262 if ((cstyle && wc > 0xFF) || fc != 'x')
2263 /* Unicode marker */
2268 goto unknown_escape;