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, 2011
6 * Thorsten Glaser <tg@mirbsd.org>
8 * Provided that these terms and disclaimer and all copyright notices
9 * are retained or reproduced in an accompanying document, permission
10 * is granted to deal in this work without restriction, including un-
11 * limited rights to use, publicly perform, distribute, sell, modify,
12 * merge, give away, or sublicence.
14 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
15 * the utmost extent permitted by applicable law, neither express nor
16 * implied; without malicious intent or gross negligence. In no event
17 * may a licensor, author or contributor be held liable for indirect,
18 * direct, other damage, loss, or other issues arising in any way out
19 * of dealing in the work, even if advised of the possibility of such
20 * damage or existence of a defect, except proven that it results out
21 * of said person's immediate fault when using the work as intended.
26 #include <sys/times.h>
32 __RCSID("$MirOS: src/bin/mksh/misc.c,v 1.172 2011/09/07 15:24:18 tg Exp $");
34 /* type bits for unsigned char */
35 unsigned char chtypes[UCHAR_MAX + 1];
37 static const unsigned char *pat_scan(const unsigned char *,
38 const unsigned char *, bool);
39 static int do_gmatch(const unsigned char *, const unsigned char *,
40 const unsigned char *, const unsigned char *);
41 static const unsigned char *cclass(const unsigned char *, int);
43 static void chvt(const char *);
46 /*XXX this should go away */
47 static int make_path(const char *, const char *, char **, XString *, int *);
49 #ifdef SETUID_CAN_FAIL_WITH_EAGAIN
50 /* we don't need to check for other codes, EPERM won't happen */
51 #define DO_SETUID(func, argvec) do { \
52 if ((func argvec) && errno == EAGAIN) \
53 errorf("%s failed with EAGAIN, probably due to a" \
54 " too low process limit; aborting", #func); \
55 } while (/* CONSTCOND */ 0)
57 #define DO_SETUID(func, argvec) func argvec
61 * Fast character classes
64 setctypes(const char *s, int t)
69 for (i = 0; i < UCHAR_MAX + 1; i++)
71 /* include \0 in C_IFS */
75 chtypes[(unsigned char)*s++] |= t;
83 for (c = 'a'; c <= 'z'; c++)
84 chtypes[c] |= C_ALPHA;
85 for (c = 'A'; c <= 'Z'; c++)
86 chtypes[c] |= C_ALPHA;
87 chtypes['_'] |= C_ALPHA;
88 setctypes("0123456789", C_DIGIT);
89 /* \0 added automatically */
90 setctypes(" \t\n|&;<>()", C_LEX1);
91 setctypes("*@#!$-?", C_VAR1);
92 setctypes(" \t\n", C_IFSWS);
93 setctypes("=-+?", C_SUBOP1);
94 setctypes("\t\n \"#$&'()*;<=>?[\\]`|", C_QUOTE);
97 /* called from XcheckN() to grow buffer */
99 Xcheck_grow_(XString *xsp, const char *xp, size_t more)
101 const char *old_beg = xsp->beg;
105 /* (xsp->len + X_EXTRA) never overflows */
106 checkoktoadd(more, xsp->len + X_EXTRA);
107 xsp->beg = aresize(xsp->beg, (xsp->len += more) + X_EXTRA, xsp->areap);
108 xsp->end = xsp->beg + xsp->len;
109 return (xsp->beg + (xp - old_beg));
112 #define SHFLAGS_DEFNS
113 #include "sh_flags.h"
115 const struct shoption options[] = {
116 #define SHFLAGS_ITEMS
117 #include "sh_flags.h"
121 * translate -o option into F* constant (also used for test -o option)
124 option(const char *n)
128 if ((n[0] == '-' || n[0] == '+') && n[1] && !n[2]) {
129 for (i = 0; i < NELEM(options); i++)
130 if (options[i].c == n[1])
132 } else for (i = 0; i < NELEM(options); i++)
133 if (options[i].name && strcmp(options[i].name, n) == 0)
139 struct options_info {
141 int opts[NELEM(options)];
144 static char *options_fmt_entry(char *, size_t, int, const void *);
145 static void printoptions(bool);
147 /* format a single select menu item */
149 options_fmt_entry(char *buf, size_t buflen, int i, const void *arg)
151 const struct options_info *oi = (const struct options_info *)arg;
153 shf_snprintf(buf, buflen, "%-*s %s",
154 oi->opt_width, options[oi->opts[i]].name,
155 Flag(oi->opts[i]) ? "on" : "off");
160 printoptions(bool verbose)
165 ssize_t n = 0, len, octs = 0;
166 struct options_info oi;
168 /* verbose version */
169 shf_puts("Current option settings\n", shl_stdout);
172 while (i < NELEM(options)) {
173 if (options[i].name) {
175 len = strlen(options[i].name);
178 len = utf_mbswidth(options[i].name);
179 if (len > oi.opt_width)
184 print_columns(shl_stdout, n, options_fmt_entry, &oi,
185 octs + 4, oi.opt_width + 4, true);
187 /* short version like AT&T ksh93 */
188 shf_puts(Tset, shl_stdout);
189 while (i < (int)NELEM(options)) {
190 if (Flag(i) && options[i].name)
191 shprintf("%s %s %s", null, "-o",
195 shf_putc('\n', shl_stdout);
203 char m[(int)FNFLAGS + 1];
206 for (i = 0; i < NELEM(options); i++)
207 if (options[i].c && Flag(i))
208 *cp++ = options[i].c;
209 strndupx(cp, m, cp - m, ATEMP);
213 /* change a Flag(*) value; takes care of special actions */
215 change_flag(enum sh_flag f, int what, unsigned int newval)
217 unsigned char oldval;
220 /* needed for tristates */
221 Flag(f) = newval ? 1 : 0;
222 #ifndef MKSH_UNEMPLOYED
224 if (what != OF_CMDLINE && newval != oldval)
232 f == FEMACS || f == FGMACS) && newval) {
236 Flag(FEMACS) = Flag(FGMACS) = 0;
237 Flag(f) = (unsigned char)newval;
238 } else if (f == FPRIVILEGED && oldval && !newval) {
239 /* Turning off -p? */
241 /*XXX this can probably be optimised */
242 kshegid = kshgid = getgid();
244 DO_SETUID(setresgid, (kshegid, kshegid, kshegid));
246 /* setgroups doesn't EAGAIN on Linux */
247 setgroups(1, &kshegid);
249 DO_SETUID(setresuid, (ksheuid, ksheuid, ksheuid));
251 /* seteuid, setegid, setgid don't EAGAIN on Linux */
252 seteuid(ksheuid = kshuid = getuid());
253 DO_SETUID(setuid, (ksheuid));
257 } else if ((f == FPOSIX || f == FSH) && newval) {
258 Flag(FPOSIX) = Flag(FSH) = Flag(FBRACEEXPAND) = 0;
259 Flag(f) = (unsigned char)newval;
261 /* Changing interactive flag? */
263 if ((what == OF_CMDLINE || what == OF_SET) && procpid == kshpid)
264 Flag(FTALKING_I) = (unsigned char)newval;
269 * Parse command line and set command arguments. Returns the index of
270 * non-option arguments, -1 if there is an error.
273 parse_args(const char **argv,
274 /* OF_CMDLINE or OF_SET */
278 static char cmd_opts[NELEM(options) + 5]; /* o:T:\0 */
279 static char set_opts[NELEM(options) + 6]; /* A:o;s\0 */
281 const char *array = NULL;
284 int optc, arrayset = 0;
285 bool sortargs = false;
287 /* First call? Build option strings... */
288 if (cmd_opts[0] == '\0') {
289 char *p = cmd_opts, *q = set_opts;
291 /* see cmd_opts[] declaration */
294 #if !defined(MKSH_SMALL) || defined(TIOCSCTTY)
298 /* see set_opts[] declaration */
305 for (i = 0; i < NELEM(options); i++) {
307 if (options[i].flags & OF_CMDLINE)
309 if (options[i].flags & OF_SET)
317 if (what == OF_CMDLINE) {
318 const char *p = argv[0], *q;
320 * Set FLOGIN before parsing options so user can clear
327 Flag(FLOGIN) = (*p == '-');
329 } else if (what == OF_FIRSTTIME) {
333 ksh_getopt_reset(&go, GF_ERROR|GF_PLUSOPT);
334 while ((optc = ksh_getopt(argv, &go, opts)) != -1) {
335 set = (go.info & GI_PLUS) ? 0 : 1;
338 if (what == OF_FIRSTTIME)
340 arrayset = set ? 1 : -1;
345 if (what == OF_FIRSTTIME)
347 if (go.optarg == NULL) {
349 * lone -o: print options
351 * Note that on the command line, -o requires
352 * an option (ie, can't get here if what is
358 i = option(go.optarg);
359 if ((i != (size_t)-1) && set == Flag(i))
361 * Don't check the context if the flag
362 * isn't changing - makes "set -o interactive"
363 * work if you're already interactive. Needed
364 * if the output of "set +o" is to be used.
367 else if ((i != (size_t)-1) && (options[i].flags & what))
368 change_flag((enum sh_flag)i, what, set);
370 bi_errorf("%s: %s", go.optarg, "bad option");
375 #if !defined(MKSH_SMALL) || defined(TIOCSCTTY)
377 if (what != OF_FIRSTTIME)
380 errorf("no TIOCSCTTY ioctl");
382 change_flag(FTALKING, OF_CMDLINE, 1);
392 if (what == OF_FIRSTTIME)
394 /* -s: sort positional params (AT&T ksh stupidity) */
395 if (what == OF_SET && optc == 's') {
399 for (i = 0; i < NELEM(options); i++)
400 if (optc == options[i].c &&
401 (what & options[i].flags)) {
402 change_flag((enum sh_flag)i, what, set);
405 if (i == NELEM(options))
406 internal_errorf("parse_args: '%c'", optc);
409 if (!(go.info & GI_MINUSMINUS) && argv[go.optind] &&
410 (argv[go.optind][0] == '-' || argv[go.optind][0] == '+') &&
411 argv[go.optind][1] == '\0') {
412 /* lone - clears -v and -x flags */
413 if (argv[go.optind][0] == '-')
414 Flag(FVERBOSE) = Flag(FXTRACE) = 0;
415 /* set skips lone - or + option */
419 /* -- means set $#/$* even if there are no arguments */
420 *setargsp = !arrayset && ((go.info & GI_MINUSMINUS) ||
424 const char *ccp = NULL;
427 ccp = skip_varname(array, false);
428 if (!ccp || !(!ccp[0] || (ccp[0] == '+' && !ccp[1]))) {
429 bi_errorf("%s: %s", array, "is not an identifier");
434 for (i = go.optind; argv[i]; i++)
436 qsort(&argv[go.optind], i - go.optind, sizeof(void *),
440 go.optind += set_array(array, tobool(arrayset > 0),
446 /* parse a decimal number: returns 0 if string isn't a number, 1 otherwise */
448 getn(const char *s, int *ai)
455 } while (ksh_isspace(c));
471 } while ((c = *s++));
480 /* getn() that prints error */
482 bi_getn(const char *as, int *ai)
486 if (!(rv = getn(as, ai)))
487 bi_errorf("%s: %s", as, "bad number");
492 * pattern simplifications:
493 * - @(x) -> x (not @(x|y) though)
497 simplify_gmatch_pattern(const unsigned char *sp)
500 unsigned char *cp, *dp;
501 const unsigned char *ps, *se;
503 cp = alloc(strlen((const void *)sp) + 1, ATEMP);
504 goto simplify_gmatch_pat1a;
506 /* foo@(b@(a)r)b@(a|a)z -> foobarb@(a|a)z */
507 simplify_gmatch_pat1:
509 simplify_gmatch_pat1a:
511 se = sp + strlen((const void *)sp);
512 while ((c = *sp++)) {
517 switch ((c = *sp++)) {
521 /* check whether it has only one clause */
522 ps = pat_scan(sp, se, true);
523 if (!ps || ps[-1] != /*(*/ ')')
526 /* copy inner clause until matching close */
528 while ((const unsigned char *)sp < ps)
530 /* skip MAGIC and closing parenthesis */
532 /* copy the rest of the pattern */
533 memmove(dp, sp, strlen((const void *)sp) + 1);
534 /* redo from start */
535 goto simplify_gmatch_pat1;
542 /* collapse adjacent asterisk wildcards */
544 while ((c = *sp++)) {
549 switch ((c = *sp++)) {
551 while (ISMAGIC(sp[0]) && sp[1] == c)
560 /* return the result, allocated from ATEMP */
564 /* -------- gmatch.c -------- */
567 * int gmatch(string, pattern)
568 * char *string, *pattern;
570 * Match a pattern as in sh(1).
571 * pattern character are prefixed with MAGIC by expand.
574 gmatchx(const char *s, const char *p, bool isfile)
580 if (s == NULL || p == NULL)
586 * isfile is false iff no syntax check has been done on
587 * the pattern. If check fails, just to a strcmp().
589 if (!isfile && !has_globbing(p, pe)) {
590 size_t len = pe - p + 1;
592 char *t = len <= sizeof(tbuf) ? tbuf : alloc(len, ATEMP);
594 return (!strcmp(t, s));
598 * since the do_gmatch() engine sucks so much, we must do some
599 * pattern simplifications
601 pnew = simplify_gmatch_pattern((const unsigned char *)p);
602 pe = pnew + strlen(pnew);
604 rv = do_gmatch((const unsigned char *)s, (const unsigned char *)se,
605 (const unsigned char *)pnew, (const unsigned char *)pe);
611 * Returns if p is a syntacticly correct globbing pattern, false
612 * if it contains no pattern characters or if there is a syntax error.
614 * - [ with no closing ]
615 * - imbalanced $(...) expression
616 * - [...] and *(...) not nested (eg, [a$(b|]c), *(a[b|c]d))
620 * if dest given, copy to dst
622 * - if magic && (no globbing || syntax error)
628 has_globbing(const char *xp, const char *xpe)
630 const unsigned char *p = (const unsigned char *) xp;
631 const unsigned char *pe = (const unsigned char *) xpe;
633 int nest = 0, bnest = 0;
634 bool saw_glob = false;
636 bool in_bracket = false;
638 for (; p < pe; p++) {
641 if ((c = *++p) == '*' || c == '?')
647 if (ISMAGIC(p[1]) && p[2] == NOT)
649 if (ISMAGIC(p[1]) && p[2] == ']')
652 /*XXX Do we need to check ranges here? POSIX Q */
653 } else if (c == ']') {
660 } else if ((c & 0x80) && vstrchr("*+?@! ", c & 0x7f)) {
666 } else if (c == '|') {
667 if (in_bracket && !bnest)
670 } else if (c == /*(*/ ')') {
679 * else must be a MAGIC-MAGIC, or MAGIC-!,
680 * MAGIC--, MAGIC-], MAGIC-{, MAGIC-, MAGIC-}
683 return (saw_glob && !in_bracket && !nest);
686 /* Function must return either 0 or 1 (assumed by code for 0x80|'!') */
688 do_gmatch(const unsigned char *s, const unsigned char *se,
689 const unsigned char *p, const unsigned char *pe)
692 const unsigned char *prest, *psub, *pnext;
693 const unsigned char *srest;
695 if (s == NULL || p == NULL)
699 sc = s < se ? *s : '\0';
708 if (sc == 0 || (p = cclass(p, sc)) == NULL)
717 s += utf_ptradj((const void *)s);
726 if (do_gmatch(s, se, p, pe))
732 * [*+?@!](pattern|pattern|..)
733 * This is also needed for ${..%..}, etc.
736 /* matches one or more times */
738 /* matches zero or more times */
740 if (!(prest = pat_scan(p, pe, false)))
743 /* take care of zero matches */
744 if (p[-1] == (0x80 | '*') &&
745 do_gmatch(s, se, prest, pe))
747 for (psub = p; ; psub = pnext) {
748 pnext = pat_scan(psub, pe, true);
749 for (srest = s; srest <= se; srest++) {
750 if (do_gmatch(s, srest, psub, pnext - 2) &&
751 (do_gmatch(srest, se, prest, pe) ||
752 (s != srest && do_gmatch(srest,
761 /* matches zero or once */
763 /* matches one of the patterns */
767 if (!(prest = pat_scan(p, pe, false)))
770 /* Take care of zero matches */
771 if (p[-1] == (0x80 | '?') &&
772 do_gmatch(s, se, prest, pe))
774 for (psub = p; ; psub = pnext) {
775 pnext = pat_scan(psub, pe, true);
776 srest = prest == pe ? se : s;
777 for (; srest <= se; srest++) {
778 if (do_gmatch(s, srest, psub, pnext - 2) &&
779 do_gmatch(srest, se, prest, pe))
787 /* matches none of the patterns */
789 if (!(prest = pat_scan(p, pe, false)))
792 for (srest = s; srest <= se; srest++) {
795 for (psub = p; ; psub = pnext) {
796 pnext = pat_scan(psub, pe, true);
797 if (do_gmatch(s, srest, psub,
806 do_gmatch(srest, se, prest, pe))
820 static const unsigned char *
821 cclass(const unsigned char *p, int sub)
823 int c, d, notp, found = 0;
824 const unsigned char *orig_p = p;
826 if ((notp = (ISMAGIC(*p) && *++p == NOT)))
832 if ((c & 0x80) && !ISMAGIC(c)) {
833 /* extended pattern matching: *+?@! */
835 /* XXX the ( char isn't handled as part of [] */
837 /* simile for @: plain (..) */
842 /* No closing ] - act as if the opening [ was quoted */
843 return (sub == '[' ? orig_p : NULL);
844 if (ISMAGIC(p[0]) && p[1] == '-' &&
845 (!ISMAGIC(p[2]) || p[3] != ']')) {
851 if ((d & 0x80) && !ISMAGIC(d))
854 /* POSIX says this is an invalid expression */
859 if (c == sub || (c <= sub && sub <= d))
861 } while (!(ISMAGIC(p[0]) && p[1] == ']'));
863 return ((found != notp) ? p+2 : NULL);
866 /* Look for next ) or | (if match_sep) in *(foo|bar) pattern */
867 static const unsigned char *
868 pat_scan(const unsigned char *p, const unsigned char *pe, bool match_sep)
872 for (; p < pe; p++) {
875 if ((*++p == /*(*/ ')' && nest-- == 0) ||
876 (*p == '|' && match_sep && nest == 0))
878 if ((*p & 0x80) && vstrchr("*+?@! ", *p & 0x7f))
885 xstrcmp(const void *p1, const void *p2)
887 return (strcmp(*(const char * const *)p1, *(const char * const *)p2));
890 /* Initialise a Getopt structure */
892 ksh_getopt_reset(Getopt *go, int flags)
904 * getopt() used for shell built-in commands, the getopts command, and
905 * command line options.
906 * A leading ':' in options means don't print errors, instead return '?'
907 * or ':' and set go->optarg to the offending option character.
908 * If GF_ERROR is set (and option doesn't start with :), errors result in
909 * a call to bi_errorf().
911 * Non-standard features:
912 * - ';' is like ':' in options, except the argument is optional
913 * (if it isn't present, optarg is set to 0).
915 * - ',' is like ':' in options, except the argument always immediately
916 * follows the option character (optarg is set to the null string if
917 * the option is missing).
918 * Used for 'read -u2', 'print -u2' and fc -40.
919 * - '#' is like ':' in options, expect that the argument is optional
920 * and must start with a digit. If the argument doesn't start with a
921 * digit, it is assumed to be missing and normal option processing
922 * continues (optarg is set to 0 if the option is missing).
923 * Used for 'typeset -LZ4'.
924 * - accepts +c as well as -c IF the GF_PLUSOPT flag is present. If an
925 * option starting with + is accepted, the GI_PLUS flag will be set
929 ksh_getopt(const char **argv, Getopt *go, const char *optionsp)
934 if (go->p == 0 || (c = argv[go->optind - 1][go->p]) == '\0') {
935 const char *arg = argv[go->optind], flag = arg ? *arg : '\0';
938 if (flag == '-' && arg[1] == '-' && arg[2] == '\0') {
941 go->info |= GI_MINUSMINUS;
946 /* neither a - nor a + (if + allowed) */
947 (!(go->flags & GF_PLUSOPT) || flag != '+')) ||
948 (c = arg[1]) == '\0') {
953 go->info &= ~(GI_MINUS|GI_PLUS);
954 go->info |= flag == '-' ? GI_MINUS : GI_PLUS;
957 if (c == '?' || c == ':' || c == ';' || c == ',' || c == '#' ||
958 !(o = cstrchr(optionsp, c))) {
959 if (optionsp[0] == ':') {
961 go->optarg = go->buf;
963 warningf(true, "%s%s-%c: %s",
964 (go->flags & GF_NONAME) ? "" : argv[0],
965 (go->flags & GF_NONAME) ? "" : ": ", c,
967 if (go->flags & GF_ERROR)
973 * : means argument must be present, may be part of option argument
974 * or the next argument
975 * ; same as : but argument may be missing
976 * , means argument is part of option argument, and may be null.
978 if (*++o == ':' || *o == ';') {
979 if (argv[go->optind - 1][go->p])
980 go->optarg = argv[go->optind - 1] + go->p;
981 else if (argv[go->optind])
982 go->optarg = argv[go->optind++];
986 if (optionsp[0] == ':') {
988 go->optarg = go->buf;
991 warningf(true, "%s%s-%c: %s",
992 (go->flags & GF_NONAME) ? "" : argv[0],
993 (go->flags & GF_NONAME) ? "" : ": ", c,
994 "requires an argument");
995 if (go->flags & GF_ERROR)
1000 } else if (*o == ',') {
1001 /* argument is attached to option character, even if null */
1002 go->optarg = argv[go->optind - 1] + go->p;
1004 } else if (*o == '#') {
1006 * argument is optional and may be attached or unattached
1007 * but must start with a digit. optarg is set to 0 if the
1008 * argument is missing.
1010 if (argv[go->optind - 1][go->p]) {
1011 if (ksh_isdigit(argv[go->optind - 1][go->p])) {
1012 go->optarg = argv[go->optind - 1] + go->p;
1017 if (argv[go->optind] && ksh_isdigit(argv[go->optind][0])) {
1018 go->optarg = argv[go->optind++];
1028 * print variable/alias value using necessary quotes
1029 * (POSIX says they should be suitable for re-entry...)
1030 * No trailing newline is printed.
1033 print_value_quoted(const char *s)
1036 bool inquote = false;
1038 /* first, check whether any quotes are needed */
1039 for (p = s; *p; p++)
1040 if (ctype(*p, C_QUOTE))
1043 /* nope, use the shortcut */
1044 shf_puts(s, shl_stdout);
1048 /* quote via state machine */
1049 for (p = s; *p; p++) {
1052 * multiple '''s or any ' at beginning of string
1053 * look nicer this way than when simply substituting
1056 shf_putc('\'', shl_stdout);
1059 shf_putc('\\', shl_stdout);
1060 } else if (!inquote) {
1061 shf_putc('\'', shl_stdout);
1064 shf_putc(*p, shl_stdout);
1067 shf_putc('\'', shl_stdout);
1071 * Print things in columns and rows - func() is called to format
1075 print_columns(struct shf *shf, int n,
1076 char *(*func)(char *, size_t, int, const void *),
1077 const void *arg, size_t max_oct, size_t max_colz, bool prefcol)
1079 int i, r, c, rows, cols, nspace, max_col;
1084 internal_warningf("print_columns called with n=%d <= 0", n);
1089 if (max_colz > 2147483647) {
1091 internal_warningf("print_columns called with max_col=%zu > INT_MAX",
1096 max_col = (int)max_colz;
1099 str = alloc(max_oct, ATEMP);
1101 /* ensure x_cols is valid first */
1102 if (x_cols < MIN_COLS)
1106 * We use (max_col + 1) to consider the space separator.
1107 * Note that no space is printed after the last column
1108 * to avoid problems with terminals that have auto-wrap.
1110 cols = x_cols / (max_col + 1);
1112 /* if we can only print one column anyway, skip the goo */
1114 for (i = 0; i < n; ++i)
1115 shf_fprintf(shf, "%s \n",
1116 (*func)(str, max_oct, i, arg));
1120 rows = (n + cols - 1) / cols;
1121 if (prefcol && cols > rows) {
1123 rows = cols > n ? n : cols;
1128 nspace = (x_cols + max_col * cols) / cols;
1131 for (r = 0; r < rows; r++) {
1132 for (c = 0; c < cols; c++) {
1135 shf_fprintf(shf, "%*s", max_col,
1136 (*func)(str, max_oct, i, arg));
1138 shf_fprintf(shf, "%*s", nspace, null);
1141 shf_putchar('\n', shf);
1147 /* Strip any nul bytes from buf - returns new length (nbytes - # of nuls) */
1149 strip_nuls(char *buf, int nbytes)
1154 * nbytes check because some systems (older FreeBSDs) have a
1157 if (nbytes && (dst = memchr(buf, '\0', nbytes))) {
1158 char *end = buf + nbytes;
1161 for (p = dst; p < end; p = q) {
1162 /* skip a block of nulls */
1163 while (++p < end && *p == '\0')
1165 /* find end of non-null block */
1166 if (!(q = memchr(p, '\0', end - p)))
1168 memmove(dst, p, q - p);
1176 * Like read(2), but if read fails due to non-blocking flag,
1177 * resets flag and restarts read.
1180 blocking_read(int fd, char *buf, size_t nbytes)
1183 bool tried_reset = false;
1185 while ((ret = read(fd, buf, nbytes)) < 0) {
1186 if (!tried_reset && errno == EAGAIN) {
1187 if (reset_nonblock(fd) > 0) {
1199 * Reset the non-blocking flag on the specified file descriptor.
1200 * Returns -1 if there was an error, 0 if non-blocking wasn't set,
1204 reset_nonblock(int fd)
1208 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1210 if (!(flags & O_NONBLOCK))
1212 flags &= ~O_NONBLOCK;
1213 if (fcntl(fd, F_SETFL, flags) < 0)
1218 /* getcwd(3) equivalent, allocates from ATEMP but doesn't resize */
1225 if ((cp = get_current_dir_name())) {
1226 strdupx(rv, cp, ATEMP);
1233 if (!getcwd((rv = alloc(PATH_MAX + 1, ATEMP)), PATH_MAX)) {
1243 do_realpath(const char *upath)
1245 char *xp, *ip, *tp, *ipath, *ldest = NULL;
1252 size_t ldestlen = 0;
1253 #define pathlen sb.st_size
1254 #define pathcnd (ldestlen < (pathlen + 1))
1256 #define pathlen PATH_MAX
1257 #define pathcnd (!ldest)
1259 /* max. recursion depth */
1262 if (upath[0] == '/') {
1263 /* upath is an absolute pathname */
1264 strdupx(ipath, upath, ATEMP);
1266 /* upath is a relative pathname, prepend cwd */
1267 if ((tp = ksh_get_wd()) == NULL || tp[0] != '/')
1269 ipath = shf_smprintf("%s%s%s", tp, "/", upath);
1273 /* ipath and upath are in memory at the same time -> unchecked */
1274 Xinit(xs, xp, strlen(ip = ipath) + 1, ATEMP);
1276 /* now jump into the deep of the loop */
1277 goto beginning_of_a_pathname;
1280 /* skip slashes in input */
1286 /* get next pathname component from input */
1288 while (*ip && *ip != '/')
1292 /* check input for "." and ".." */
1295 /* just continue with the next one */
1297 else if (len == 2 && tp[1] == '.') {
1298 /* strip off last pathname component */
1299 while (xp > Xstring(xs, xp))
1302 /* then continue with the next one */
1307 /* store output position away, then append slash to output */
1308 pos = Xsavepos(xs, xp);
1309 /* 1 for the '/' and len + 1 for tp and the NUL from below */
1310 XcheckN(xs, xp, 1 + len + 1);
1313 /* append next pathname component to output */
1314 memcpy(xp, tp, len);
1318 /* lstat the current output, see if it's a symlink */
1319 if (lstat(Xstring(xs, xp), &sb)) {
1321 if (errno == ENOENT) {
1322 /* because the pathname does not exist */
1324 /* skip any trailing slashes */
1326 /* no more components left? */
1328 /* we can still return successfully */
1330 /* more components left? fall through */
1332 /* not ENOENT or not at the end of ipath */
1336 /* check if we encountered a symlink? */
1337 if (S_ISLNK(sb.st_mode)) {
1338 /* reached maximum recursion depth? */
1340 /* yep, prevent infinite loops */
1345 /* get symlink(7) target */
1348 if (notoktoadd(pathlen, 1)) {
1349 errno = ENAMETOOLONG;
1353 ldest = aresize(ldest, pathlen + 1, ATEMP);
1355 llen = readlink(Xstring(xs, xp), ldest, pathlen);
1362 * restart if symlink target is an absolute path,
1363 * otherwise continue with currently resolved prefix
1365 /* append rest of current input path to link target */
1366 tp = shf_smprintf("%s%s%s", ldest, *ip ? "/" : "", ip);
1367 afree(ipath, ATEMP);
1369 if (ldest[0] != '/') {
1370 /* symlink target is a relative path */
1371 xp = Xrestpos(xs, xp, pos);
1373 /* symlink target is an absolute path */
1374 xp = Xstring(xs, xp);
1375 beginning_of_a_pathname:
1376 /* assert: (ip == ipath)[0] == '/' */
1377 /* assert: xp == xs.beg => start of path */
1379 /* exactly two leading slashes? (SUSv4 3.266) */
1380 if (ip[1] == '/' && ip[2] != '/') {
1381 /* keep them, e.g. for UNC pathnames */
1386 /* otherwise (no symlink) merely go on */
1390 * either found the target and successfully resolved it,
1391 * or found its parent directory and may create it
1393 if (Xlength(xs, xp) == 0)
1395 * if the resolved pathname is "", make it "/",
1396 * otherwise do not add a trailing slash
1402 * if source path had a trailing slash, check if target path
1403 * is not a non-directory existing file
1405 if (ip > ipath && ip[-1] == '/') {
1406 if (stat(Xstring(xs, xp), &sb)) {
1407 if (errno != ENOENT)
1409 } else if (!S_ISDIR(sb.st_mode)) {
1413 /* target now either does not exist or is a directory */
1416 /* return target path */
1418 afree(ldest, ATEMP);
1419 afree(ipath, ATEMP);
1420 return (Xclose(xs, xp));
1423 /* save; freeing memory might trash it */
1426 afree(ldest, ATEMP);
1427 afree(ipath, ATEMP);
1437 * Makes a filename into result using the following algorithm.
1438 * - make result NULL
1439 * - if file starts with '/', append file to result & set cdpathp to NULL
1440 * - if file starts with ./ or ../ append cwd and file to result
1441 * and set cdpathp to NULL
1442 * - if the first element of cdpathp doesnt start with a '/' xx or '.' xx
1443 * then cwd is appended to result.
1444 * - the first element of cdpathp is appended to result
1445 * - file is appended to result
1446 * - cdpathp is set to the start of the next element in cdpathp (or NULL
1447 * if there are no more elements.
1448 * The return value indicates whether a non-null element from cdpathp
1449 * was appended to result.
1452 make_path(const char *cwd, const char *file,
1453 /* pointer to colon-separated list */
1459 bool use_cdpath = true;
1461 size_t len, plen = 0;
1462 char *xp = Xstring(*xsp, xp);
1467 if (file[0] == '/') {
1471 if (file[0] == '.') {
1476 if (c == '/' || c == '\0')
1483 else if (use_cdpath) {
1486 for (pend = plist; *pend && *pend != ':'; pend++)
1488 plen = pend - plist;
1489 *cdpathp = *pend ? pend + 1 : NULL;
1492 if ((!use_cdpath || !plen || plist[0] != '/') &&
1495 XcheckN(*xsp, xp, len);
1496 memcpy(xp, cwd, len);
1498 if (cwd[len - 1] != '/')
1499 Xput(*xsp, xp, '/');
1501 *phys_pathp = Xlength(*xsp, xp);
1502 if (use_cdpath && plen) {
1503 XcheckN(*xsp, xp, plen);
1504 memcpy(xp, plist, plen);
1506 if (plist[plen - 1] != '/')
1507 Xput(*xsp, xp, '/');
1512 len = strlen(file) + 1;
1513 XcheckN(*xsp, xp, len);
1514 memcpy(xp, file, len);
1523 * Simplify pathnames containing "." and ".." entries.
1525 * simplify_path(this) = that
1526 * /a/b/c/./../d/.. /a/b
1527 * //./C/foo/bar/../baz //C/foo/baz
1529 * /foo/../../bar /bar
1530 * /foo/./blah/.. /foo
1534 * foo/../../../bar ../../bar
1537 simplify_path(char *p)
1539 char *dp, *ip, *sp, *tp;
1547 /* exactly two leading slashes? (SUSv4 3.266) */
1548 if (p[1] == '/' && p[2] != '/')
1549 /* keep them, e.g. for UNC pathnames */
1559 /* skip slashes in input */
1565 /* get next pathname component from input */
1567 while (*ip && *ip != '/')
1571 /* check input for "." and ".." */
1574 /* just continue with the next one */
1576 else if (len == 2 && tp[1] == '.') {
1577 /* parent level, but how? */
1579 /* absolute path, only one way */
1580 goto strip_last_component;
1582 /* relative path, with subpaths */
1584 strip_last_component:
1585 /* strip off last pathname component */
1590 /* relative path, at its beginning */
1592 /* or already dotdot-slash'd */
1594 /* keep dotdot-slash if not absolute */
1600 /* then continue with the next one */
1608 /* append next pathname component to output */
1609 memmove(dp, tp, len);
1612 /* append slash if we continue */
1614 /* try next component */
1617 /* empty path -> dot */
1618 *dp++ = needslash ? '/' : '.';
1623 set_current_wd(const char *nwd)
1625 char *allocd = NULL;
1628 allocd = ksh_get_wd();
1629 nwd = allocd ? allocd : null;
1632 afree(current_wd, APERM);
1633 strdupx(current_wd, nwd, APERM);
1635 afree(allocd, ATEMP);
1639 c_cd(const char **wp)
1641 int optc, rv, phys_path;
1642 bool physical = tobool(Flag(FPHYSICAL));
1643 /* was a node from cdpath added in? */
1645 /* show where we went?, error for $PWD */
1646 bool printpath = false, eflag = false;
1647 struct tbl *pwd_s, *oldpwd_s;
1649 char *dir, *allocd = NULL, *tryp, *pwd, *cdpath;
1651 while ((optc = ksh_getopt(wp, &builtin_opt, "eLP")) != -1)
1665 wp += builtin_opt.optind;
1667 if (Flag(FRESTRICTED)) {
1668 bi_errorf("restricted shell - can't cd");
1672 pwd_s = global("PWD");
1673 oldpwd_s = global("OLDPWD");
1676 /* No arguments - go home */
1677 if ((dir = str_val(global("HOME"))) == null) {
1678 bi_errorf("no home directory (HOME not set)");
1681 } else if (!wp[1]) {
1682 /* One argument: - or dir */
1683 strdupx(allocd, wp[0], ATEMP);
1684 if (ksh_isdash((dir = allocd))) {
1685 afree(allocd, ATEMP);
1687 dir = str_val(oldpwd_s);
1689 bi_errorf("no OLDPWD");
1694 } else if (!wp[2]) {
1695 /* Two arguments - substitute arg1 in PWD for arg2 */
1696 size_t ilen, olen, nlen, elen;
1699 if (!current_wd[0]) {
1700 bi_errorf("can't determine current directory");
1704 * substitute arg1 for arg2 in current path.
1705 * if the first substitution fails because the cd fails
1706 * we could try to find another substitution. For now
1709 if ((cp = strstr(current_wd, wp[0])) == NULL) {
1710 bi_errorf("bad substitution");
1714 * ilen = part of current_wd before wp[0]
1715 * elen = part of current_wd after wp[0]
1716 * because current_wd and wp[1] need to be in memory at the
1717 * same time beforehand the addition can stay unchecked
1719 ilen = cp - current_wd;
1720 olen = strlen(wp[0]);
1721 nlen = strlen(wp[1]);
1722 elen = strlen(current_wd + ilen + olen) + 1;
1723 dir = allocd = alloc(ilen + nlen + elen, ATEMP);
1724 memcpy(dir, current_wd, ilen);
1725 memcpy(dir + ilen, wp[1], nlen);
1726 memcpy(dir + ilen + nlen, current_wd + ilen + olen, elen);
1729 bi_errorf("too many arguments");
1734 /* only a first guess; make_path will enlarge xs if necessary */
1735 XinitN(xs, 1024, ATEMP);
1737 XinitN(xs, PATH_MAX, ATEMP);
1740 cdpath = str_val(global("CDPATH"));
1742 cdnode = make_path(current_wd, dir, &cdpath, &xs, &phys_path);
1744 rv = chdir(tryp = Xstring(xs, xp) + phys_path);
1746 simplify_path(Xstring(xs, xp));
1747 rv = chdir(tryp = Xstring(xs, xp));
1749 } while (rv < 0 && cdpath != NULL);
1753 bi_errorf("%s: %s", dir, "bad directory");
1755 bi_errorf("%s: %s", tryp, strerror(errno));
1756 afree(allocd, ATEMP);
1763 /* allocd (above) => dir, which is no longer used */
1764 afree(allocd, ATEMP);
1767 /* Clear out tracked aliases with relative paths */
1771 * Set OLDPWD (note: unsetting OLDPWD does not disable this
1772 * setting in AT&T ksh)
1775 /* Ignore failure (happens if readonly or integer) */
1776 setstr(oldpwd_s, current_wd, KSH_RETURN_ERROR);
1778 if (Xstring(xs, xp)[0] != '/') {
1780 } else if (!physical) {
1781 goto norealpath_PWD;
1782 } else if ((pwd = allocd = do_realpath(Xstring(xs, xp))) == NULL) {
1786 pwd = Xstring(xs, xp);
1793 set_current_wd(ptmp);
1794 /* Ignore failure (happens if readonly or integer) */
1795 setstr(pwd_s, ptmp, KSH_RETURN_ERROR);
1797 set_current_wd(null);
1798 pwd = Xstring(xs, xp);
1799 /* XXX unset $PWD? */
1803 if (printpath || cdnode)
1804 shprintf("%s\n", pwd);
1806 afree(allocd, ATEMP);
1813 extern void chvt_reinit(void);
1816 chvt(const char *fn)
1823 memcpy(dv, "-/dev/null", sizeof("-/dev/null"));
1826 if (stat(fn, &sb)) {
1827 memcpy(dv, "/dev/ttyC", 9);
1828 strlcpy(dv + 9, fn, sizeof(dv) - 9);
1829 if (stat(dv, &sb)) {
1830 strlcpy(dv + 8, fn, sizeof(dv) - 8);
1832 errorf("%s: %s %s", "chvt",
1833 "can't find tty", fn);
1837 if (!(sb.st_mode & S_IFCHR))
1838 errorf("%s %s %s", "chvt: not a char", "device", fn);
1839 if ((sb.st_uid != 0) && chown(fn, 0, 0))
1840 warningf(false, "%s: %s %s", "chvt", "can't chown root", fn);
1841 if (((sb.st_mode & 07777) != 0600) && chmod(fn, (mode_t)0600))
1842 warningf(false, "%s: %s %s", "chvt", "can't chmod 0600", fn);
1846 warningf(false, "%s: %s %s", "chvt",
1847 "new shell is potentially insecure, can't revoke",
1850 if ((fd = open(fn, O_RDWR)) == -1) {
1852 if ((fd = open(fn, O_RDWR)) == -1)
1853 errorf("%s: %s %s", "chvt", "can't open", fn);
1857 errorf("%s: %s %s", "chvt", "fork", "failed");
1864 errorf("%s: %s %s", "chvt", "setsid", "failed");
1866 if (ioctl(fd, TIOCSCTTY, NULL) == -1)
1867 errorf("%s: %s %s", "chvt", "TIOCSCTTY", "failed");
1868 if (tcflush(fd, TCIOFLUSH))
1869 errorf("%s: %s %s", "chvt", "TCIOFLUSH", "failed");
1871 ksh_dup2(fd, 0, false);
1872 ksh_dup2(fd, 1, false);
1873 ksh_dup2(fd, 2, false);
1877 register uint32_t h;
1880 NZATUpdateMem(h, &rndsetupstate, sizeof(rndsetupstate));
1889 #define assert_eq(name, a, b) char name[a == b ? 1 : -1]
1890 #define assert_ge(name, a, b) char name[a >= b ? 1 : -1]
1891 assert_ge(intsize_is_okay, sizeof(int), 4);
1892 assert_eq(intsizes_are_okay, sizeof(int), sizeof(unsigned int));
1893 assert_ge(longsize_is_okay, sizeof(long), sizeof(int));
1894 assert_eq(arisize_is_okay, sizeof(mksh_ari_t), 4);
1895 assert_eq(uarisize_is_okay, sizeof(mksh_uari_t), 4);
1896 assert_eq(sizesizes_are_okay, sizeof(size_t), sizeof(ssize_t));
1897 assert_eq(ptrsizes_are_okay, sizeof(ptrdiff_t), sizeof(void *));
1898 assert_eq(ptrsize_is_sizet, sizeof(ptrdiff_t), sizeof(size_t));
1899 /* formatting routines assume this */
1900 assert_ge(ptr_fits_in_long, sizeof(long), sizeof(size_t));
1903 strchr(char *p, int ch)
1915 strstr(char *b, const char *l)
1920 if ((first = *l++) == '\0')
1924 while ((c = *b++) != first)
1927 if (strncmp(b, l, n))
1933 #if !HAVE_STRCASESTR
1935 stristr(const char *b, const char *l)
1940 if ((first = *l++), ((first = ksh_tolower(first)) == '\0'))
1944 while ((c = *b++), ((c = ksh_tolower(c)) != first))
1947 if (strncasecmp(b, l, n))
1955 strndup_(const char *src, size_t len, Area *ap)
1960 dst = alloc(len + 1, ap);
1961 memcpy(dst, src, len);
1968 strdup_(const char *src, Area *ap)
1970 return (src == NULL ? NULL : strndup_(src, strlen(src), ap));
1975 #define INVTCK(r,t) do { \
1976 r.tv_usec = ((t) % (1000000 / CLK_TCK)) * (1000000 / CLK_TCK); \
1977 r.tv_sec = (t) / CLK_TCK; \
1978 } while (/* CONSTCOND */ 0)
1981 getrusage(int what, struct rusage *ru)
1986 if (/* ru == NULL || */ times(&tms) == (clock_t)-1)
1994 case RUSAGE_CHILDREN:
2002 INVTCK(ru->ru_utime, u);
2003 INVTCK(ru->ru_stime, s);
2009 * process the string available via fg (get a char)
2010 * and fp (put back a char) for backslash escapes,
2011 * assuming the first call to *fg gets the char di-
2012 * rectly after the backslash; return the character
2013 * (0..0xFF), Unicode (wc + 0x100), or -1 if no known
2014 * escape sequence was found
2017 unbksl(bool cstyle, int (*fg)(void), void (*fp)(int))
2025 * according to the comments in pdksh, \007 seems
2026 * to be more portable than \a (due to HP-UX cc,
2027 * Ultrix cc, old pcc, etc.) so we avoid the escape
2028 * sequence altogether in mksh and assume ASCII
2037 goto unknown_escape;
2058 /* assume ASCII here as well */
2069 goto unknown_escape;
2075 * look for an octal number with up to three
2076 * digits, not counting the leading zero;
2077 * convert it to a raw octet
2082 if ((c = (*fg)()) >= '0' && c <= '7')
2083 wc = (wc << 3) + (c - '0');
2091 if (/* CONSTCOND */ 0)
2095 if (/* CONSTCOND */ 0)
2098 i = cstyle ? -1 : 2;
2100 * x: look for a hexadecimal number with up to
2101 * two (C style: arbitrary) digits; convert
2102 * to raw octet (C style: Unicode if >0xFF)
2103 * u/U: look for a hexadecimal number with up to
2104 * four (U: eight) digits; convert to Unicode
2109 if ((c = (*fg)()) >= '0' && c <= '9')
2111 else if (c >= 'A' && c <= 'F')
2113 else if (c >= 'a' && c <= 'f')
2121 if ((cstyle && wc > 0xFF) || fc != 'x')
2122 /* Unicode marker */
2127 goto unknown_escape;