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, 2017
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.255 2017/04/12 16:46:22 tg Exp $");
44 /* type bits for unsigned char */
45 unsigned char chtypes[UCHAR_MAX + 1];
47 static const unsigned char *pat_scan(const unsigned char *,
48 const unsigned char *, bool) MKSH_A_PURE;
49 static int do_gmatch(const unsigned char *, const unsigned char *,
50 const unsigned char *, const unsigned char *) MKSH_A_PURE;
51 static const unsigned char *gmatch_cclass(const unsigned char *, unsigned char)
54 static void chvt(const Getopt *);
57 /*XXX this should go away */
58 static int make_path(const char *, const char *, char **, XString *, int *);
60 #ifdef SETUID_CAN_FAIL_WITH_EAGAIN
61 /* we don't need to check for other codes, EPERM won't happen */
62 #define DO_SETUID(func, argvec) do { \
63 if ((func argvec) && errno == EAGAIN) \
64 errorf("%s failed with EAGAIN, probably due to a" \
65 " too low process limit; aborting", #func); \
66 } while (/* CONSTCOND */ 0)
68 #define DO_SETUID(func, argvec) func argvec
72 * Fast character classes
75 setctypes(const char *s, int t)
80 while (++i <= UCHAR_MAX)
82 /* include '\0' in C_IFS */
86 chtypes[(unsigned char)*s++] |= t;
92 setctypes(letters_uc, C_ALPHX);
93 setctypes(letters_lc, C_ALPHX);
94 chtypes['_'] |= C_ALPHX;
95 setctypes("0123456789", C_DIGIT);
96 setctypes(TC_LEX1, C_LEX1);
97 setctypes("*@#!$-?", C_VAR1);
98 setctypes(TC_IFSWS, C_IFSWS);
99 setctypes("=-+?", C_SUBOP1);
100 setctypes("\t\n \"#$&'()*;<=>?[\\]`|", C_QUOTE);
103 /* called from XcheckN() to grow buffer */
105 Xcheck_grow(XString *xsp, const char *xp, size_t more)
107 const char *old_beg = xsp->beg;
111 /* (xsp->len + X_EXTRA) never overflows */
112 checkoktoadd(more, xsp->len + X_EXTRA);
113 xsp->beg = aresize(xsp->beg, (xsp->len += more) + X_EXTRA, xsp->areap);
114 xsp->end = xsp->beg + xsp->len;
115 return (xsp->beg + (xp - old_beg));
119 #define SHFLAGS_DEFNS
120 #define FN(sname,cname,flags,ochar) \
121 static const struct { \
122 /* character flag (if any) */ \
125 unsigned char optflags; \
126 /* long name of option */ \
127 char name[sizeof(sname)]; \
128 } shoptione_ ## cname = { \
129 ochar, flags, sname \
131 #include "sh_flags.gen"
133 #define OFC(i) (options[i][-2])
134 #define OFF(i) (((const unsigned char *)options[i])[-1])
135 #define OFN(i) (options[i])
137 const char * const options[] = {
138 #define SHFLAGS_ITEMS
139 #include "sh_flags.gen"
143 * translate -o option into F* constant (also used for test -o option)
146 option(const char *n)
150 if ((n[0] == '-' || n[0] == '+') && n[1] && !n[2])
151 while (i < NELEM(options)) {
157 while (i < NELEM(options)) {
158 if (!strcmp(OFN(i), n))
166 struct options_info {
168 int opts[NELEM(options)];
171 static void options_fmt_entry(char *, size_t, unsigned int, const void *);
172 static void printoptions(bool);
174 /* format a single select menu item */
176 options_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
178 const struct options_info *oi = (const struct options_info *)arg;
180 shf_snprintf(buf, buflen, "%-*s %s",
181 oi->opt_width, OFN(oi->opts[i]),
182 Flag(oi->opts[i]) ? "on" : "off");
186 printoptions(bool verbose)
191 size_t n = 0, len, octs = 0;
192 struct options_info oi;
193 struct columnise_opts co;
195 /* verbose version */
196 shf_puts("Current option settings\n", shl_stdout);
199 while (i < NELEM(options)) {
200 if ((len = strlen(OFN(i)))) {
204 len = utf_mbswidth(OFN(i));
205 if ((int)len > oi.opt_width)
206 oi.opt_width = (int)len;
212 co.prefcol = co.do_last = true;
213 print_columns(&co, n, options_fmt_entry, &oi,
214 octs + 4, oi.opt_width + 4);
216 /* short version like AT&T ksh93 */
217 shf_puts(Tset, shl_stdout);
218 while (i < NELEM(options)) {
219 if (Flag(i) && OFN(i)[0])
220 shprintf(" -o %s", OFN(i));
223 shf_putc('\n', shl_stdout);
231 char c, m[(int)FNFLAGS + 1];
234 while (i < NELEM(options)) {
235 if ((c = OFC(i)) && Flag(i))
239 strndupx(cp, m, cp - m, ATEMP);
243 /* change a Flag(*) value; takes care of special actions */
245 change_flag(enum sh_flag f, int what, bool newset)
247 unsigned char oldval;
248 unsigned char newval = (newset ? 1 : 0);
251 change_xtrace(newval, true);
255 Flag(f) = newval = (newset ? 1 : 0);
256 #ifndef MKSH_UNEMPLOYED
258 if (what != OF_CMDLINE && newval != oldval)
262 #ifndef MKSH_NO_CMDLINE_EDITING
267 f == FEMACS || f == FGMACS) && newval) {
271 Flag(FEMACS) = Flag(FGMACS) = 0;
275 if (f == FPRIVILEGED && oldval && !newval) {
276 /* Turning off -p? */
278 /*XXX this can probably be optimised */
279 kshegid = kshgid = getgid();
280 ksheuid = kshuid = getuid();
282 DO_SETUID(setresgid, (kshegid, kshegid, kshegid));
284 /* setgroups doesn't EAGAIN on Linux */
285 setgroups(1, &kshegid);
287 DO_SETUID(setresuid, (ksheuid, ksheuid, ksheuid));
288 #else /* !HAVE_SETRESUGID */
289 /* setgid, setegid, seteuid don't EAGAIN on Linux */
291 #ifndef MKSH__NO_SETEUGID
294 DO_SETUID(setuid, (ksheuid));
295 #ifndef MKSH__NO_SETEUGID
298 #endif /* !HAVE_SETRESUGID */
299 } else if ((f == FPOSIX || f == FSH) && newval) {
300 /* Turning on -o posix or -o sh? */
301 Flag(FBRACEEXPAND) = 0;
302 } else if (f == FTALKING) {
303 /* Changing interactive flag? */
304 if ((what == OF_CMDLINE || what == OF_SET) && procpid == kshpid)
305 Flag(FTALKING_I) = newval;
310 change_xtrace(unsigned char newval, bool dosnapshot)
312 static bool in_xtrace;
317 if (!dosnapshot && newval == Flag(FXTRACE))
320 if (Flag(FXTRACE) == 2) {
321 shf_putc('\n', shl_xtrace);
323 shf_flush(shl_xtrace);
326 if (!dosnapshot && Flag(FXTRACE) == 1)
334 shf_flush(shl_xtrace);
335 if (shl_xtrace->fd != 2)
336 close(shl_xtrace->fd);
337 if (!newval || (shl_xtrace->fd = savefd(2)) == -1)
341 if ((Flag(FXTRACE) = newval) == 2) {
344 shf_puts(substitute(str_val(global("PS4")), 0), shl_xtrace);
351 * Parse command line and set command arguments. Returns the index of
352 * non-option arguments, -1 if there is an error.
355 parse_args(const char **argv,
356 /* OF_FIRSTTIME, OF_CMDLINE, or OF_SET */
360 static const char cmd_opts[] =
361 #define SHFLAGS_NOT_SET
362 #define SHFLAGS_OPTCS
363 #include "sh_flags.gen"
364 #undef SHFLAGS_NOT_SET
366 static const char set_opts[] =
367 #define SHFLAGS_NOT_CMD
368 #define SHFLAGS_OPTCS
369 #include "sh_flags.gen"
370 #undef SHFLAGS_NOT_CMD
374 const char *array = NULL;
377 int optc, arrayset = 0;
378 bool sortargs = false;
379 bool fcompatseen = false;
381 if (what == OF_CMDLINE) {
382 const char *p = argv[0], *q;
384 * Set FLOGIN before parsing options so user can clear
389 if (mksh_cdirsep(*q++))
391 Flag(FLOGIN) = (*p == '-');
393 } else if (what == OF_FIRSTTIME) {
397 ksh_getopt_reset(&go, GF_ERROR|GF_PLUSOPT);
398 while ((optc = ksh_getopt(argv, &go, opts)) != -1) {
399 set = tobool(!(go.info & GI_PLUS));
402 if (what == OF_FIRSTTIME)
404 arrayset = set ? 1 : -1;
409 if (what == OF_FIRSTTIME)
411 if (go.optarg == NULL) {
413 * lone -o: print options
415 * Note that on the command line, -o requires
416 * an option (ie, can't get here if what is
422 i = option(go.optarg);
423 if ((i == FPOSIX || i == FSH) && set && !fcompatseen) {
425 * If running 'set -o posix' or
426 * 'set -o sh', turn off the other;
427 * if running 'set -o posix -o sh'
428 * allow both to be set though.
434 if ((i != (size_t)-1) && (set ? 1U : 0U) == Flag(i))
436 * Don't check the context if the flag
437 * isn't changing - makes "set -o interactive"
438 * work if you're already interactive. Needed
439 * if the output of "set +o" is to be used.
442 else if ((i != (size_t)-1) && (OFF(i) & what))
443 change_flag((enum sh_flag)i, what, set);
445 bi_errorf(Tf_sD_s, go.optarg,
453 if (what != OF_FIRSTTIME)
455 #ifndef KSH_CHVT_CODE
456 errorf("no TIOCSCTTY ioctl");
458 change_flag(FTALKING, OF_CMDLINE, true);
468 if (what == OF_FIRSTTIME)
470 /* -s: sort positional params (AT&T ksh stupidity) */
471 if (what == OF_SET && optc == 's') {
475 for (i = 0; i < NELEM(options); i++)
476 if (optc == OFC(i) &&
478 change_flag((enum sh_flag)i, what, set);
481 if (i == NELEM(options))
482 internal_errorf("parse_args: '%c'", optc);
485 if (!(go.info & GI_MINUSMINUS) && argv[go.optind] &&
486 (argv[go.optind][0] == '-' || argv[go.optind][0] == '+') &&
487 argv[go.optind][1] == '\0') {
488 /* lone - clears -v and -x flags */
489 if (argv[go.optind][0] == '-') {
491 change_xtrace(0, false);
493 /* set skips lone - or + option */
497 /* -- means set $#/$* even if there are no arguments */
498 *setargsp = !arrayset && ((go.info & GI_MINUSMINUS) ||
502 const char *ccp = NULL;
505 ccp = skip_varname(array, false);
506 if (!ccp || !(!ccp[0] || (ccp[0] == '+' && !ccp[1]))) {
507 bi_errorf(Tf_sD_s, array, Tnot_ident);
512 for (i = go.optind; argv[i]; i++)
514 qsort(&argv[go.optind], i - go.optind, sizeof(void *),
518 go.optind += set_array(array, tobool(arrayset > 0),
524 /* parse a decimal number: returns 0 if string isn't a number, 1 otherwise */
526 getn(const char *s, int *ai)
536 } while (ksh_isspace(c));
551 if (num.u > 214748364U)
552 /* overflow on multiplication */
554 num.u = num.u * 10U + (unsigned int)ksh_numdig(c);
555 /* now: num.u <= 2147483649U */
556 } while ((c = *s++));
558 if (num.u > (neg ? 2147483648U : 2147483647U))
559 /* overflow for signed 32-bit int */
569 * pattern simplifications:
570 * - @(x) -> x (not @(x|y) though)
574 simplify_gmatch_pattern(const unsigned char *sp)
577 unsigned char *cp, *dp;
578 const unsigned char *ps, *se;
580 cp = alloc(strlen((const void *)sp) + 1, ATEMP);
581 goto simplify_gmatch_pat1a;
583 /* foo@(b@(a)r)b@(a|a)z -> foobarb@(a|a)z */
584 simplify_gmatch_pat1:
586 simplify_gmatch_pat1a:
588 se = sp + strlen((const void *)sp);
589 while ((c = *sp++)) {
594 switch ((c = *sp++)) {
598 /* check whether it has only one clause */
599 ps = pat_scan(sp, se, true);
600 if (!ps || ps[-1] != /*(*/ ')')
603 /* copy inner clause until matching close */
605 while ((const unsigned char *)sp < ps)
607 /* skip MAGIC and closing parenthesis */
609 /* copy the rest of the pattern */
610 memmove(dp, sp, strlen((const void *)sp) + 1);
611 /* redo from start */
612 goto simplify_gmatch_pat1;
619 /* collapse adjacent asterisk wildcards */
621 while ((c = *sp++)) {
626 switch ((c = *sp++)) {
628 while (ISMAGIC(sp[0]) && sp[1] == c)
637 /* return the result, allocated from ATEMP */
641 /* -------- gmatch.c -------- */
644 * int gmatch(string, pattern)
645 * char *string, *pattern;
647 * Match a pattern as in sh(1).
648 * pattern character are prefixed with MAGIC by expand.
651 gmatchx(const char *s, const char *p, bool isfile)
657 if (s == NULL || p == NULL)
663 * isfile is false iff no syntax check has been done on
664 * the pattern. If check fails, just to a strcmp().
666 if (!isfile && !has_globbing(p, pe)) {
667 size_t len = pe - p + 1;
669 char *t = len <= sizeof(tbuf) ? tbuf : alloc(len, ATEMP);
671 return (!strcmp(t, s));
675 * since the do_gmatch() engine sucks so much, we must do some
676 * pattern simplifications
678 pnew = simplify_gmatch_pattern((const unsigned char *)p);
679 pe = pnew + strlen(pnew);
681 rv = do_gmatch((const unsigned char *)s, (const unsigned char *)se,
682 (const unsigned char *)pnew, (const unsigned char *)pe);
688 * Returns if p is a syntacticly correct globbing pattern, false
689 * if it contains no pattern characters or if there is a syntax error.
691 * - [ with no closing ]
692 * - imbalanced $(...) expression
693 * - [...] and *(...) not nested (eg, [a$(b|]c), *(a[b|c]d))
697 * if dest given, copy to dst
699 * - if magic && (no globbing || syntax error)
705 has_globbing(const char *xp, const char *xpe)
707 const unsigned char *p = (const unsigned char *) xp;
708 const unsigned char *pe = (const unsigned char *) xpe;
710 int nest = 0, bnest = 0;
711 bool saw_glob = false;
713 bool in_bracket = false;
715 for (; p < pe; p++) {
718 if ((c = *++p) == '*' || c == '?')
724 if (ISMAGIC(p[1]) && p[2] == '!')
726 if (ISMAGIC(p[1]) && p[2] == ']')
729 /*XXX Do we need to check ranges here? POSIX Q */
730 } else if (c == ']') {
737 } else if ((c & 0x80) && vstrchr("*+?@! ", c & 0x7f)) {
743 } else if (c == '|') {
744 if (in_bracket && !bnest)
747 } else if (c == /*(*/ ')') {
756 * else must be a MAGIC-MAGIC, or MAGIC-!,
757 * MAGIC--, MAGIC-], MAGIC-{, MAGIC-, MAGIC-}
760 return (saw_glob && !in_bracket && !nest);
763 /* Function must return either 0 or 1 (assumed by code for 0x80|'!') */
765 do_gmatch(const unsigned char *s, const unsigned char *se,
766 const unsigned char *p, const unsigned char *pe)
768 unsigned char sc, pc;
769 const unsigned char *prest, *psub, *pnext;
770 const unsigned char *srest;
772 if (s == NULL || p == NULL)
776 sc = s < se ? *s : '\0';
785 if (sc == 0 || (p = gmatch_cclass(p, sc)) == NULL)
794 s += utf_ptradj((const void *)s);
803 if (do_gmatch(s, se, p, pe))
809 * [*+?@!](pattern|pattern|..)
810 * This is also needed for ${..%..}, etc.
813 /* matches one or more times */
815 /* matches zero or more times */
817 if (!(prest = pat_scan(p, pe, false)))
820 /* take care of zero matches */
821 if (p[-1] == (0x80 | '*') &&
822 do_gmatch(s, se, prest, pe))
824 for (psub = p; ; psub = pnext) {
825 pnext = pat_scan(psub, pe, true);
826 for (srest = s; srest <= se; srest++) {
827 if (do_gmatch(s, srest, psub, pnext - 2) &&
828 (do_gmatch(srest, se, prest, pe) ||
829 (s != srest && do_gmatch(srest,
838 /* matches zero or once */
840 /* matches one of the patterns */
844 if (!(prest = pat_scan(p, pe, false)))
847 /* Take care of zero matches */
848 if (p[-1] == (0x80 | '?') &&
849 do_gmatch(s, se, prest, pe))
851 for (psub = p; ; psub = pnext) {
852 pnext = pat_scan(psub, pe, true);
853 srest = prest == pe ? se : s;
854 for (; srest <= se; srest++) {
855 if (do_gmatch(s, srest, psub, pnext - 2) &&
856 do_gmatch(srest, se, prest, pe))
864 /* matches none of the patterns */
866 if (!(prest = pat_scan(p, pe, false)))
869 for (srest = s; srest <= se; srest++) {
872 for (psub = p; ; psub = pnext) {
873 pnext = pat_scan(psub, pe, true);
874 if (do_gmatch(s, srest, psub,
883 do_gmatch(srest, se, prest, pe))
897 static const unsigned char *
898 gmatch_cclass(const unsigned char *p, unsigned char sub)
901 bool notp, found = false;
902 const unsigned char *orig_p = p;
904 if ((notp = tobool(ISMAGIC(*p) && *++p == '!')))
910 if ((c & 0x80) && !ISMAGIC(c)) {
911 /* extended pattern matching: *+?@! */
913 /* XXX the ( char isn't handled as part of [] */
915 /* simile for @: plain (..) */
920 /* No closing ] - act as if the opening [ was quoted */
921 return (sub == '[' ? orig_p : NULL);
922 if (ISMAGIC(p[0]) && p[1] == '-' &&
923 (!ISMAGIC(p[2]) || p[3] != ']')) {
929 if ((d & 0x80) && !ISMAGIC(d))
932 /* POSIX says this is an invalid expression */
937 if (c == sub || (c <= sub && sub <= d))
939 } while (!(ISMAGIC(p[0]) && p[1] == ']'));
941 return ((found != notp) ? p+2 : NULL);
944 /* Look for next ) or | (if match_sep) in *(foo|bar) pattern */
945 static const unsigned char *
946 pat_scan(const unsigned char *p, const unsigned char *pe, bool match_sep)
950 for (; p < pe; p++) {
953 if ((*++p == /*(*/ ')' && nest-- == 0) ||
954 (*p == '|' && match_sep && nest == 0))
956 if ((*p & 0x80) && vstrchr("*+?@! ", *p & 0x7f))
963 xstrcmp(const void *p1, const void *p2)
965 return (strcmp(*(const char * const *)p1, *(const char * const *)p2));
968 /* Initialise a Getopt structure */
970 ksh_getopt_reset(Getopt *go, int flags)
982 * getopt() used for shell built-in commands, the getopts command, and
983 * command line options.
984 * A leading ':' in options means don't print errors, instead return '?'
985 * or ':' and set go->optarg to the offending option character.
986 * If GF_ERROR is set (and option doesn't start with :), errors result in
987 * a call to bi_errorf().
989 * Non-standard features:
990 * - ';' is like ':' in options, except the argument is optional
991 * (if it isn't present, optarg is set to 0).
993 * - ',' is like ':' in options, except the argument always immediately
994 * follows the option character (optarg is set to the null string if
995 * the option is missing).
996 * Used for 'read -u2', 'print -u2' and fc -40.
997 * - '#' is like ':' in options, expect that the argument is optional
998 * and must start with a digit. If the argument doesn't start with a
999 * digit, it is assumed to be missing and normal option processing
1000 * continues (optarg is set to 0 if the option is missing).
1001 * Used for 'typeset -LZ4'.
1002 * - accepts +c as well as -c IF the GF_PLUSOPT flag is present. If an
1003 * option starting with + is accepted, the GI_PLUS flag will be set
1007 ksh_getopt(const char **argv, Getopt *go, const char *optionsp)
1012 if (go->p == 0 || (c = argv[go->optind - 1][go->p]) == '\0') {
1013 const char *arg = argv[go->optind], flag = arg ? *arg : '\0';
1016 if (flag == '-' && ksh_isdash(arg + 1)) {
1019 go->info |= GI_MINUSMINUS;
1024 /* neither a - nor a + (if + allowed) */
1025 (!(go->flags & GF_PLUSOPT) || flag != '+')) ||
1026 (c = arg[1]) == '\0') {
1031 go->info &= ~(GI_MINUS|GI_PLUS);
1032 go->info |= flag == '-' ? GI_MINUS : GI_PLUS;
1035 if (c == '?' || c == ':' || c == ';' || c == ',' || c == '#' ||
1036 !(o = cstrchr(optionsp, c))) {
1037 if (optionsp[0] == ':') {
1039 go->optarg = go->buf;
1041 warningf(true, Tf_optfoo,
1042 (go->flags & GF_NONAME) ? "" : argv[0],
1043 (go->flags & GF_NONAME) ? "" : Tcolsp,
1044 c, Tunknown_option);
1045 if (go->flags & GF_ERROR)
1051 * : means argument must be present, may be part of option argument
1052 * or the next argument
1053 * ; same as : but argument may be missing
1054 * , means argument is part of option argument, and may be null.
1056 if (*++o == ':' || *o == ';') {
1057 if (argv[go->optind - 1][go->p])
1058 go->optarg = argv[go->optind - 1] + go->p;
1059 else if (argv[go->optind])
1060 go->optarg = argv[go->optind++];
1064 if (optionsp[0] == ':') {
1066 go->optarg = go->buf;
1069 warningf(true, Tf_optfoo,
1070 (go->flags & GF_NONAME) ? "" : argv[0],
1071 (go->flags & GF_NONAME) ? "" : Tcolsp,
1073 if (go->flags & GF_ERROR)
1078 } else if (*o == ',') {
1079 /* argument is attached to option character, even if null */
1080 go->optarg = argv[go->optind - 1] + go->p;
1082 } else if (*o == '#') {
1084 * argument is optional and may be attached or unattached
1085 * but must start with a digit. optarg is set to 0 if the
1086 * argument is missing.
1088 if (argv[go->optind - 1][go->p]) {
1089 if (ksh_isdigit(argv[go->optind - 1][go->p])) {
1090 go->optarg = argv[go->optind - 1] + go->p;
1095 if (argv[go->optind] && ksh_isdigit(argv[go->optind][0])) {
1096 go->optarg = argv[go->optind++];
1106 * print variable/alias value using necessary quotes
1107 * (POSIX says they should be suitable for re-entry...)
1108 * No trailing newline is printed.
1111 print_value_quoted(struct shf *shf, const char *s)
1114 const unsigned char *p = (const unsigned char *)s;
1115 bool inquote = true;
1117 /* first, check whether any quotes are needed */
1118 while ((c = *p++) >= 32)
1119 if (ctype(c, C_QUOTE))
1122 p = (const unsigned char *)s;
1125 /* nope, use the shortcut */
1130 /* otherwise, quote nicely via state machine */
1131 while ((c = *p++) != 0) {
1134 * multiple single quotes or any of them
1135 * at the beginning of a string look nicer
1136 * this way than when simply substituting
1139 shf_putc('\'', shf);
1142 shf_putc('\\', shf);
1143 } else if (!inquote) {
1144 shf_putc('\'', shf);
1153 /* use $'...' quote format */
1155 shf_putc('\'', shf);
1156 while ((c = *p) != 0) {
1158 n = utf_mbtowc(&wc, (const char *)p);
1159 if (n != (size_t)-1) {
1161 shf_fprintf(shf, "\\u%04X", wc);
1167 /* see unbksl() in this file for comments */
1197 /* take E not e because \e is \ in *roff */
1201 shf_putc('\\', shf);
1206 if (c < 32 || c > 0x7E) {
1209 shf_fprintf(shf, "\\%03o", c);
1220 shf_putc('\'', shf);
1224 * Print things in columns and rows - func() is called to format
1228 print_columns(struct columnise_opts *opts, unsigned int n,
1229 void (*func)(char *, size_t, unsigned int, const void *),
1230 const void *arg, size_t max_oct, size_t max_colz)
1232 unsigned int i, r = 0, c, rows, cols, nspace, max_col;
1238 if (max_colz > 2147483646) {
1240 internal_warningf("print_columns called with %s=%zu >= INT_MAX",
1241 "max_col", max_colz);
1245 max_col = (unsigned int)max_colz;
1247 if (max_oct > 2147483646) {
1249 internal_warningf("print_columns called with %s=%zu >= INT_MAX",
1250 "max_oct", max_oct);
1255 str = alloc(max_oct, ATEMP);
1258 * We use (max_col + 2) to consider the separator space.
1259 * Note that no spaces are printed after the last column
1260 * to avoid problems with terminals that have auto-wrap,
1261 * but we need to also take this into account in x_cols.
1263 cols = (x_cols + 1) / (max_col + 2);
1265 /* if we can only print one column anyway, skip the goo */
1269 shf_putc(opts->linesep, opts->shf);
1271 (*func)(str, max_oct, r++, arg);
1272 shf_puts(str, opts->shf);
1277 rows = (n + cols - 1) / cols;
1278 if (opts->prefcol && cols > rows) {
1280 rows = (n + cols - 1) / cols;
1283 nspace = (x_cols - max_col * cols) / cols;
1289 shf_putchar(opts->linesep, opts->shf);
1291 for (c = 0; c < cols; c++) {
1292 if ((i = c * rows + r) >= n)
1294 (*func)(str, max_oct, i, arg);
1296 shf_puts(str, opts->shf);
1298 shf_fprintf(opts->shf, "%*s%*s",
1299 (int)max_col, str, (int)nspace, null);
1305 shf_putchar(opts->linesep, opts->shf);
1309 /* strip all NUL bytes from buf; output is NUL-terminated if stripped */
1311 strip_nuls(char *buf, size_t len)
1315 if (!len || !(dp = memchr(buf, '\0', len)))
1322 while (cp++ < ep && *cp == '\0')
1324 while (cp < ep && *cp != '\0')
1327 goto cp_has_nul_byte;
1333 * Like read(2), but if read fails due to non-blocking flag,
1334 * resets flag and restarts read.
1337 blocking_read(int fd, char *buf, size_t nbytes)
1340 bool tried_reset = false;
1342 while ((ret = read(fd, buf, nbytes)) < 0) {
1343 if (!tried_reset && errno == EAGAIN) {
1344 if (reset_nonblock(fd) > 0) {
1356 * Reset the non-blocking flag on the specified file descriptor.
1357 * Returns -1 if there was an error, 0 if non-blocking wasn't set,
1361 reset_nonblock(int fd)
1365 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1367 if (!(flags & O_NONBLOCK))
1369 flags &= ~O_NONBLOCK;
1370 if (fcntl(fd, F_SETFL, flags) < 0)
1375 /* getcwd(3) equivalent, allocates from ATEMP but doesn't resize */
1379 #ifdef MKSH__NO_PATH_MAX
1382 if ((cp = get_current_dir_name())) {
1383 strdupx(rv, cp, ATEMP);
1390 if (!getcwd((rv = alloc(PATH_MAX + 1, ATEMP)), PATH_MAX)) {
1404 do_realpath(const char *upath)
1406 char *xp, *ip, *tp, *ipath, *ldest = NULL;
1411 #ifdef MKSH__NO_PATH_MAX
1412 size_t ldestlen = 0;
1413 #define pathlen sb.st_size
1414 #define pathcnd (ldestlen < (pathlen + 1))
1416 #define pathlen PATH_MAX
1417 #define pathcnd (!ldest)
1419 /* max. recursion depth */
1422 if (mksh_abspath(upath)) {
1423 /* upath is an absolute pathname */
1424 strdupx(ipath, upath, ATEMP);
1426 /* upath is a relative pathname, prepend cwd */
1427 if ((tp = ksh_get_wd()) == NULL || !mksh_abspath(tp))
1429 ipath = shf_smprintf(Tf_sss, tp, "/", upath);
1433 /* ipath and upath are in memory at the same time -> unchecked */
1434 Xinit(xs, xp, strlen(ip = ipath) + 1, ATEMP);
1436 /* now jump into the deep of the loop */
1437 goto beginning_of_a_pathname;
1440 /* skip slashes in input */
1441 while (mksh_cdirsep(*ip))
1446 /* get next pathname component from input */
1448 while (*ip && !mksh_cdirsep(*ip))
1452 /* check input for "." and ".." */
1455 /* just continue with the next one */
1457 else if (len == 2 && tp[1] == '.') {
1458 /* strip off last pathname component */
1459 while (xp > Xstring(xs, xp))
1460 if (mksh_cdirsep(*--xp))
1462 /* then continue with the next one */
1467 /* store output position away, then append slash to output */
1468 pos = Xsavepos(xs, xp);
1469 /* 1 for the '/' and len + 1 for tp and the NUL from below */
1470 XcheckN(xs, xp, 1 + len + 1);
1473 /* append next pathname component to output */
1474 memcpy(xp, tp, len);
1478 /* lstat the current output, see if it's a symlink */
1479 if (mksh_lstat(Xstring(xs, xp), &sb)) {
1481 if (errno == ENOENT) {
1482 /* because the pathname does not exist */
1483 while (mksh_cdirsep(*ip))
1484 /* skip any trailing slashes */
1486 /* no more components left? */
1488 /* we can still return successfully */
1490 /* more components left? fall through */
1492 /* not ENOENT or not at the end of ipath */
1496 /* check if we encountered a symlink? */
1497 if (S_ISLNK(sb.st_mode)) {
1498 #ifndef MKSH__NO_SYMLINK
1499 /* reached maximum recursion depth? */
1501 /* yep, prevent infinite loops */
1506 /* get symlink(7) target */
1508 #ifdef MKSH__NO_PATH_MAX
1509 if (notoktoadd(pathlen, 1)) {
1510 errno = ENAMETOOLONG;
1514 ldest = aresize(ldest, pathlen + 1, ATEMP);
1516 llen = readlink(Xstring(xs, xp), ldest, pathlen);
1523 * restart if symlink target is an absolute path,
1524 * otherwise continue with currently resolved prefix
1526 /* append rest of current input path to link target */
1527 tp = shf_smprintf(Tf_sss, ldest, *ip ? "/" : "", ip);
1528 afree(ipath, ATEMP);
1530 if (!mksh_abspath(ldest)) {
1531 /* symlink target is a relative path */
1532 xp = Xrestpos(xs, xp, pos);
1536 /* symlink target is an absolute path */
1537 xp = Xstring(xs, xp);
1538 beginning_of_a_pathname:
1539 /* assert: mksh_cdirsep((ip == ipath)[0]) */
1540 /* assert: xp == xs.beg => start of path */
1542 /* exactly two leading slashes? (SUSv4 3.266) */
1543 if (ip[1] == ip[0] && !mksh_cdirsep(ip[2])) {
1544 /* keep them, e.g. for UNC pathnames */
1549 /* otherwise (no symlink) merely go on */
1553 * either found the target and successfully resolved it,
1554 * or found its parent directory and may create it
1556 if (Xlength(xs, xp) == 0)
1558 * if the resolved pathname is "", make it "/",
1559 * otherwise do not add a trailing slash
1565 * if source path had a trailing slash, check if target path
1566 * is not a non-directory existing file
1568 if (ip > ipath && mksh_cdirsep(ip[-1])) {
1569 if (stat(Xstring(xs, xp), &sb)) {
1570 if (errno != ENOENT)
1572 } else if (!S_ISDIR(sb.st_mode)) {
1576 /* target now either does not exist or is a directory */
1579 /* return target path */
1580 afree(ldest, ATEMP);
1581 afree(ipath, ATEMP);
1582 return (Xclose(xs, xp));
1585 /* save; freeing memory might trash it */
1587 afree(ldest, ATEMP);
1588 afree(ipath, ATEMP);
1598 * Makes a filename into result using the following algorithm.
1599 * - make result NULL
1600 * - if file starts with '/', append file to result & set cdpathp to NULL
1601 * - if file starts with ./ or ../ append cwd and file to result
1602 * and set cdpathp to NULL
1603 * - if the first element of cdpathp doesnt start with a '/' xx or '.' xx
1604 * then cwd is appended to result.
1605 * - the first element of cdpathp is appended to result
1606 * - file is appended to result
1607 * - cdpathp is set to the start of the next element in cdpathp (or NULL
1608 * if there are no more elements.
1609 * The return value indicates whether a non-null element from cdpathp
1610 * was appended to result.
1613 make_path(const char *cwd, const char *file,
1614 /* pointer to colon-separated list */
1620 bool use_cdpath = true;
1622 size_t len, plen = 0;
1623 char *xp = Xstring(*xsp, xp);
1628 if (mksh_abspath(file)) {
1632 if (file[0] == '.') {
1637 if (mksh_cdirsep(c) || c == '\0')
1644 else if (use_cdpath) {
1647 while (*pend && *pend != MKSH_PATHSEPC)
1649 plen = pend - plist;
1650 *cdpathp = *pend ? pend + 1 : NULL;
1653 if ((!use_cdpath || !plen || !mksh_abspath(plist)) &&
1656 XcheckN(*xsp, xp, len);
1657 memcpy(xp, cwd, len);
1659 if (!mksh_cdirsep(cwd[len - 1]))
1660 Xput(*xsp, xp, '/');
1662 *phys_pathp = Xlength(*xsp, xp);
1663 if (use_cdpath && plen) {
1664 XcheckN(*xsp, xp, plen);
1665 memcpy(xp, plist, plen);
1667 if (!mksh_cdirsep(plist[plen - 1]))
1668 Xput(*xsp, xp, '/');
1673 len = strlen(file) + 1;
1674 XcheckN(*xsp, xp, len);
1675 memcpy(xp, file, len);
1684 * Simplify pathnames containing "." and ".." entries.
1686 * simplify_path(this) = that
1687 * /a/b/c/./../d/.. /a/b
1688 * //./C/foo/bar/../baz //C/foo/baz
1690 * /foo/../../bar /bar
1691 * /foo/./blah/.. /foo
1695 * foo/../../../bar ../../bar
1698 simplify_path(char *p)
1700 char *dp, *ip, *sp, *tp;
1711 /* exactly two leading slashes? (SUSv4 3.266) */
1712 if (p[1] == p[0] && !mksh_cdirsep(p[2]))
1713 /* keep them, e.g. for UNC pathnames */
1723 /* skip slashes in input */
1724 while (mksh_cdirsep(*ip))
1729 /* get next pathname component from input */
1731 while (*ip && !mksh_cdirsep(*ip))
1735 /* check input for "." and ".." */
1738 /* just continue with the next one */
1740 else if (len == 2 && tp[1] == '.') {
1741 /* parent level, but how? */
1742 if (mksh_abspath(p))
1743 /* absolute path, only one way */
1744 goto strip_last_component;
1746 /* relative path, with subpaths */
1748 strip_last_component:
1749 /* strip off last pathname component */
1751 if (mksh_cdirsep(*--dp))
1754 /* relative path, at its beginning */
1756 /* or already dotdot-slash'd */
1758 /* keep dotdot-slash if not absolute */
1764 /* then continue with the next one */
1772 /* append next pathname component to output */
1773 memmove(dp, tp, len);
1776 /* append slash if we continue */
1778 /* try next component */
1781 /* empty path -> dot */
1782 *dp++ = needslash ? '/' : '.';
1787 set_current_wd(const char *nwd)
1789 char *allocd = NULL;
1792 allocd = ksh_get_wd();
1793 nwd = allocd ? allocd : null;
1796 afree(current_wd, APERM);
1797 strdupx(current_wd, nwd, APERM);
1799 afree(allocd, ATEMP);
1803 c_cd(const char **wp)
1805 int optc, rv, phys_path;
1806 bool physical = tobool(Flag(FPHYSICAL));
1807 /* was a node from cdpath added in? */
1809 /* show where we went?, error for $PWD */
1810 bool printpath = false, eflag = false;
1811 struct tbl *pwd_s, *oldpwd_s;
1813 char *dir, *allocd = NULL, *tryp, *pwd, *cdpath;
1815 while ((optc = ksh_getopt(wp, &builtin_opt, "eLP")) != -1)
1829 wp += builtin_opt.optind;
1831 if (Flag(FRESTRICTED)) {
1832 bi_errorf(Tcant_cd);
1836 pwd_s = global(TPWD);
1837 oldpwd_s = global(TOLDPWD);
1840 /* No arguments - go home */
1841 if ((dir = str_val(global("HOME"))) == null) {
1842 bi_errorf("no home directory (HOME not set)");
1845 } else if (!wp[1]) {
1846 /* One argument: - or dir */
1847 strdupx(allocd, wp[0], ATEMP);
1848 if (ksh_isdash((dir = allocd))) {
1849 afree(allocd, ATEMP);
1851 dir = str_val(oldpwd_s);
1853 bi_errorf(Tno_OLDPWD);
1858 } else if (!wp[2]) {
1859 /* Two arguments - substitute arg1 in PWD for arg2 */
1860 size_t ilen, olen, nlen, elen;
1863 if (!current_wd[0]) {
1864 bi_errorf("can't determine current directory");
1868 * substitute arg1 for arg2 in current path.
1869 * if the first substitution fails because the cd fails
1870 * we could try to find another substitution. For now
1873 if ((cp = strstr(current_wd, wp[0])) == NULL) {
1874 bi_errorf(Tbadsubst);
1878 * ilen = part of current_wd before wp[0]
1879 * elen = part of current_wd after wp[0]
1880 * because current_wd and wp[1] need to be in memory at the
1881 * same time beforehand the addition can stay unchecked
1883 ilen = cp - current_wd;
1884 olen = strlen(wp[0]);
1885 nlen = strlen(wp[1]);
1886 elen = strlen(current_wd + ilen + olen) + 1;
1887 dir = allocd = alloc(ilen + nlen + elen, ATEMP);
1888 memcpy(dir, current_wd, ilen);
1889 memcpy(dir + ilen, wp[1], nlen);
1890 memcpy(dir + ilen + nlen, current_wd + ilen + olen, elen);
1893 bi_errorf(Ttoo_many_args);
1897 #ifdef MKSH__NO_PATH_MAX
1898 /* only a first guess; make_path will enlarge xs if necessary */
1899 XinitN(xs, 1024, ATEMP);
1901 XinitN(xs, PATH_MAX, ATEMP);
1904 cdpath = str_val(global("CDPATH"));
1906 cdnode = make_path(current_wd, dir, &cdpath, &xs, &phys_path);
1908 rv = chdir(tryp = Xstring(xs, xp) + phys_path);
1910 simplify_path(Xstring(xs, xp));
1911 rv = chdir(tryp = Xstring(xs, xp));
1913 } while (rv < 0 && cdpath != NULL);
1917 bi_errorf(Tf_sD_s, dir, "bad directory");
1919 bi_errorf(Tf_sD_s, tryp, cstrerror(errno));
1920 afree(allocd, ATEMP);
1927 /* allocd (above) => dir, which is no longer used */
1928 afree(allocd, ATEMP);
1931 /* Clear out tracked aliases with relative paths */
1935 * Set OLDPWD (note: unsetting OLDPWD does not disable this
1936 * setting in AT&T ksh)
1939 /* Ignore failure (happens if readonly or integer) */
1940 setstr(oldpwd_s, current_wd, KSH_RETURN_ERROR);
1942 if (!mksh_abspath(Xstring(xs, xp))) {
1944 } else if (!physical) {
1945 goto norealpath_PWD;
1946 } else if ((pwd = allocd = do_realpath(Xstring(xs, xp))) == NULL) {
1950 pwd = Xstring(xs, xp);
1957 set_current_wd(ptmp);
1958 /* Ignore failure (happens if readonly or integer) */
1959 setstr(pwd_s, ptmp, KSH_RETURN_ERROR);
1961 set_current_wd(null);
1962 pwd = Xstring(xs, xp);
1963 /* XXX unset $PWD? */
1967 if (printpath || cdnode)
1968 shprintf(Tf_sN, pwd);
1970 afree(allocd, ATEMP);
1976 #ifdef KSH_CHVT_CODE
1977 extern void chvt_reinit(void);
1980 chvt(const Getopt *go)
1982 const char *dv = go->optarg;
1996 if (stat(dv, &sb)) {
1997 cp = shf_smprintf("/dev/ttyC%s", dv);
1999 if (stat(dv, &sb)) {
2000 memmove(cp + 1, cp, /* /dev/tty */ 8);
2002 if (stat(dv, &sb)) {
2003 errorf(Tf_sD_sD_s, "chvt",
2004 "can't find tty", go->optarg);
2008 if (!(sb.st_mode & S_IFCHR))
2009 errorf(Tf_sD_sD_s, "chvt", "not a char device", dv);
2010 #ifndef MKSH_DISABLE_REVOKE_WARNING
2014 warningf(false, Tf_sD_s_s, "chvt",
2015 "new shell is potentially insecure, can't revoke",
2020 if ((fd = binopen2(dv, O_RDWR)) < 0) {
2022 if ((fd = binopen2(dv, O_RDWR)) < 0) {
2023 errorf(Tf_sD_s_s, "chvt", Tcant_open, dv);
2026 if (go->optarg[0] != '!') {
2029 errorf(Tf_sD_s_s, "chvt", "fork", "failed");
2037 errorf(Tf_sD_s_s, "chvt", "setsid", "failed");
2038 if (go->optarg[0] != '-') {
2039 if (ioctl(fd, TIOCSCTTY, NULL) == -1)
2040 errorf(Tf_sD_s_s, "chvt", "TIOCSCTTY", "failed");
2041 if (tcflush(fd, TCIOFLUSH))
2042 errorf(Tf_sD_s_s, "chvt", "TCIOFLUSH", "failed");
2044 ksh_dup2(fd, 0, false);
2045 ksh_dup2(fd, 1, false);
2046 ksh_dup2(fd, 2, false);
2049 rndset((unsigned long)chvt_rndsetup(go, sizeof(Getopt)));
2056 strchr(char *p, int ch)
2068 strstr(char *b, const char *l)
2073 if ((first = *l++) == '\0')
2077 while ((c = *b++) != first)
2080 if (strncmp(b, l, n))
2086 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
2088 strndup_i(const char *src, size_t len, Area *ap)
2093 dst = alloc(len + 1, ap);
2094 memcpy(dst, src, len);
2101 strdup_i(const char *src, Area *ap)
2103 return (src == NULL ? NULL : strndup_i(src, strlen(src), ap));
2108 #define INVTCK(r,t) do { \
2109 r.tv_usec = ((t) % (1000000 / CLK_TCK)) * (1000000 / CLK_TCK); \
2110 r.tv_sec = (t) / CLK_TCK; \
2111 } while (/* CONSTCOND */ 0)
2114 getrusage(int what, struct rusage *ru)
2119 if (/* ru == NULL || */ times(&tms) == (clock_t)-1)
2127 case RUSAGE_CHILDREN:
2135 INVTCK(ru->ru_utime, u);
2136 INVTCK(ru->ru_stime, s);
2142 * process the string available via fg (get a char)
2143 * and fp (put back a char) for backslash escapes,
2144 * assuming the first call to *fg gets the char di-
2145 * rectly after the backslash; return the character
2146 * (0..0xFF), Unicode (wc + 0x100), or -1 if no known
2147 * escape sequence was found
2150 unbksl(bool cstyle, int (*fg)(void), void (*fp)(int))
2152 int wc, i, c, fc, n;
2158 * according to the comments in pdksh, \007 seems
2159 * to be more portable than \a (due to HP-UX cc,
2160 * Ultrix cc, old pcc, etc.) so we avoid the escape
2161 * sequence altogether in mksh and assume ASCII
2170 goto unknown_escape;
2191 /* assume ASCII here as well */
2202 goto unknown_escape;
2208 * look for an octal number with up to three
2209 * digits, not counting the leading zero;
2210 * convert it to a raw octet
2215 if ((c = (*fg)()) >= ord('0') && c <= ord('7'))
2216 wc = (wc << 3) + ksh_numdig(c);
2224 if (/* CONSTCOND */ 0)
2228 if (/* CONSTCOND */ 0)
2231 i = cstyle ? -1 : 2;
2233 * x: look for a hexadecimal number with up to
2234 * two (C style: arbitrary) digits; convert
2235 * to raw octet (C style: Unicode if >0xFF)
2236 * u/U: look for a hexadecimal number with up to
2237 * four (U: eight) digits; convert to Unicode
2241 while (n < i || i == -1) {
2243 if ((c = (*fg)()) >= ord('0') && c <= ord('9'))
2244 wc += ksh_numdig(c);
2245 else if (c >= ord('A') && c <= ord('F'))
2246 wc += ksh_numuc(c) + 10;
2247 else if (c >= ord('a') && c <= ord('f'))
2248 wc += ksh_numlc(c) + 10;
2257 goto unknown_escape;
2258 if ((cstyle && wc > 0xFF) || fc != 'x')
2259 /* Unicode marker */
2264 goto unknown_escape;