hush: fix ${##}, ${#?}, ${#!} handling
[oweals/busybox.git] / shell / shell_common.c
index e9effd2d0885108c58b287dc9a6f704a37a8c36d..a9f8d84130d509a393ca40cf8f35457ec1fb4b4a 100644 (file)
  */
 #include "libbb.h"
 #include "shell_common.h"
+#include <sys/resource.h> /* getrlimit */
 
 const char defifsvar[] ALIGN1 = "IFS= \t\n";
+const char defoptindvar[] ALIGN1 = "OPTIND=1";
 
 
 int FAST_FUNC is_well_formed_var_name(const char *s, char terminator)
@@ -36,6 +38,10 @@ int FAST_FUNC is_well_formed_var_name(const char *s, char terminator)
 
 /* read builtin */
 
+/* Needs to be interruptible: shell must handle traps and shell-special signals
+ * while inside read. To implement this, be sure to not loop on EINTR
+ * and return errno == EINTR reliably.
+ */
 //TODO: use more efficient setvar() which takes a pointer to malloced "VAR=VAL"
 //string. hush naturally has it, and ash has setvareq().
 //Here we can simply store "VAR=" at buffer start and store read data directly
@@ -51,8 +57,10 @@ shell_builtin_read(void FAST_FUNC (*setvar)(const char *name, const char *val),
        const char *opt_u
 )
 {
+       struct pollfd pfd[1];
+#define fd (pfd[0].fd) /* -u FD */
+       unsigned err;
        unsigned end_ms; /* -t TIMEOUT */
-       int fd; /* -u FD */
        int nchars; /* -n NUM */
        char **pp;
        char *buffer;
@@ -62,6 +70,8 @@ shell_builtin_read(void FAST_FUNC (*setvar)(const char *name, const char *val),
        int startword;
        smallint backslash;
 
+       errno = err = 0;
+
        pp = argv;
        while (*pp) {
                if (!is_well_formed_var_name(*pp, '\0')) {
@@ -79,38 +89,43 @@ shell_builtin_read(void FAST_FUNC (*setvar)(const char *name, const char *val),
                        return "invalid count";
                /* note: "-n 0": off (bash 3.2 does this too) */
        }
+
        end_ms = 0;
-       if (opt_t) {
+       if (opt_t && !ENABLE_FEATURE_SH_READ_FRAC) {
                end_ms = bb_strtou(opt_t, NULL, 10);
-               if (errno || end_ms > UINT_MAX / 2048)
+               if (errno)
                        return "invalid timeout";
+               if (end_ms > UINT_MAX / 2048) /* be safely away from overflow */
+                       end_ms = UINT_MAX / 2048;
                end_ms *= 1000;
-#if 0 /* even bash has no -t N.NNN support */
-               ts.tv_sec = bb_strtou(opt_t, &p, 10);
-               ts.tv_usec = 0;
-               /* EINVAL means number is ok, but not terminated by NUL */
-               if (*p == '.' && errno == EINVAL) {
-                       char *p2;
-                       if (*++p) {
-                               int scale;
-                               ts.tv_usec = bb_strtou(p, &p2, 10);
-                               if (errno)
-                                       return "invalid timeout";
-                               scale = p2 - p;
-                               /* normalize to usec */
-                               if (scale > 6)
+       }
+       if (opt_t && ENABLE_FEATURE_SH_READ_FRAC) {
+               /* bash 4.3 (maybe earlier) supports -t N.NNNNNN */
+               char *p;
+               /* Eat up to three fractional digits */
+               int frac_digits = 3 + 1;
+
+               end_ms = bb_strtou(opt_t, &p, 10);
+               if (end_ms > UINT_MAX / 2048) /* be safely away from overflow */
+                       end_ms = UINT_MAX / 2048;
+
+               if (errno) {
+                       /* EINVAL = number is ok, but not NUL terminated */
+                       if (errno != EINVAL || *p != '.')
+                               return "invalid timeout";
+                       /* Do not check the rest: bash allows "0.123456xyz" */
+                       while (*++p && --frac_digits) {
+                               end_ms *= 10;
+                               end_ms += (*p - '0');
+                               if ((unsigned char)(*p - '0') > 9)
                                        return "invalid timeout";
-                               while (scale++ < 6)
-                                       ts.tv_usec *= 10;
                        }
-               } else if (ts.tv_sec < 0 || errno) {
-                       return "invalid timeout";
                }
-               if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
-                       return "invalid timeout";
+               while (--frac_digits > 0) {
+                       end_ms *= 10;
                }
-#endif /* if 0 */
        }
+
        fd = STDIN_FILENO;
        if (opt_u) {
                fd = bb_strtou(opt_u, NULL, 10);
@@ -118,6 +133,19 @@ shell_builtin_read(void FAST_FUNC (*setvar)(const char *name, const char *val),
                        return "invalid file descriptor";
        }
 
+       if (opt_t && end_ms == 0) {
+               /* "If timeout is 0, read returns immediately, without trying
+                * to read any data. The exit status is 0 if input is available
+                * on the specified file descriptor, non-zero otherwise."
+                * bash seems to ignore -p PROMPT for this use case.
+                */
+               int r;
+               pfd[0].events = POLLIN;
+               r = poll(pfd, 1, /*timeout:*/ 0);
+               /* Return 0 only if poll returns 1 ("one fd ready"), else return 1: */
+               return (const char *)(uintptr_t)(r <= 0);
+       }
+
        if (opt_p && isatty(fd)) {
                fputs(opt_p, stderr);
                fflush_all();
@@ -131,7 +159,13 @@ shell_builtin_read(void FAST_FUNC (*setvar)(const char *name, const char *val),
                old_tty = tty;
                if (nchars) {
                        tty.c_lflag &= ~ICANON;
-                       tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
+                       // Setting it to more than 1 breaks poll():
+                       // it blocks even if there's data. !??
+                       //tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
+                       /* reads will block only if < 1 char is available */
+                       tty.c_cc[VMIN] = 1;
+                       /* no timeout (reads block forever) */
+                       tty.c_cc[VTIME] = 0;
                }
                if (read_flags & BUILTIN_READ_SILENT) {
                        tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
@@ -146,46 +180,62 @@ shell_builtin_read(void FAST_FUNC (*setvar)(const char *name, const char *val),
        retval = (const char *)(uintptr_t)0;
        startword = 1;
        backslash = 0;
-       if (end_ms) /* NB: end_ms stays nonzero: */
-               end_ms = ((unsigned)monotonic_ms() + end_ms) | 1;
+       if (opt_t)
+               end_ms += (unsigned)monotonic_ms();
        buffer = NULL;
        bufpos = 0;
        do {
                char c;
+               int timeout;
 
-               if (end_ms) {
-                       int timeout;
-                       struct pollfd pfd[1];
+               if ((bufpos & 0xff) == 0)
+                       buffer = xrealloc(buffer, bufpos + 0x101);
 
-                       pfd[0].fd = fd;
-                       pfd[0].events = POLLIN;
+               timeout = -1;
+               if (opt_t) {
                        timeout = end_ms - (unsigned)monotonic_ms();
-                       if (timeout <= 0 /* already late? */
-                        || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
-                       ) { /* timed out! */
+                       /* ^^^^^^^^^^^^^ all values are unsigned,
+                        * wrapping math is used here, good even if
+                        * 32-bit unix time wrapped (year 2038+).
+                        */
+                       if (timeout <= 0) { /* already late? */
                                retval = (const char *)(uintptr_t)1;
                                goto ret;
                        }
                }
 
-               if ((bufpos & 0xff) == 0)
-                       buffer = xrealloc(buffer, bufpos + 0x100);
-               if (nonblock_safe_read(fd, &buffer[bufpos], 1) != 1) {
+               /* We must poll even if timeout is -1:
+                * we want to be interrupted if signal arrives,
+                * regardless of SA_RESTART-ness of that signal!
+                */
+               errno = 0;
+               pfd[0].events = POLLIN;
+               if (poll(pfd, 1, timeout) <= 0) {
+                       /* timed out, or EINTR */
+                       err = errno;
+                       retval = (const char *)(uintptr_t)1;
+                       goto ret;
+               }
+               if (read(fd, &buffer[bufpos], 1) != 1) {
+                       err = errno;
                        retval = (const char *)(uintptr_t)1;
                        break;
                }
+
                c = buffer[bufpos];
                if (c == '\0')
                        continue;
-               if (backslash) {
-                       backslash = 0;
-                       if (c != '\n')
-                               goto put;
-                       continue;
-               }
-               if (!(read_flags & BUILTIN_READ_RAW) && c == '\\') {
-                       backslash = 1;
-                       continue;
+               if (!(read_flags & BUILTIN_READ_RAW)) {
+                       if (backslash) {
+                               backslash = 0;
+                               if (c != '\n')
+                                       goto put;
+                               continue;
+                       }
+                       if (c == '\\') {
+                               backslash = 1;
+                               continue;
+                       }
                }
                if (c == '\n')
                        break;
@@ -240,7 +290,10 @@ shell_builtin_read(void FAST_FUNC (*setvar)(const char *name, const char *val),
        free(buffer);
        if (read_flags & BUILTIN_READ_SILENT)
                tcsetattr(fd, TCSANOW, &old_tty);
+
+       errno = err;
        return retval;
+#undef fd
 }
 
 /* ulimit builtin */
@@ -286,6 +339,12 @@ static const struct limits limits_tbl[] = {
 #ifdef RLIMIT_LOCKS
        { RLIMIT_LOCKS,         0,      'w',    "locks" },
 #endif
+#ifdef RLIMIT_NICE
+       { RLIMIT_NICE,          0,      'e',    "scheduling priority" },
+#endif
+#ifdef RLIMIT_RTPRIO
+       { RLIMIT_RTPRIO,        0,      'r',    "real-time priority" },
+#endif
 };
 
 enum {
@@ -294,7 +353,7 @@ enum {
 };
 
 /* "-": treat args as parameters of option with ASCII code 1 */
-static const char ulimit_opt_string[] = "-HSa"
+static const char ulimit_opt_string[] ALIGN1 = "-HSa"
 #ifdef RLIMIT_FSIZE
                        "f::"
 #endif
@@ -327,6 +386,12 @@ static const char ulimit_opt_string[] = "-HSa"
 #endif
 #ifdef RLIMIT_LOCKS
                        "w::"
+#endif
+#ifdef RLIMIT_NICE
+                       "e::"
+#endif
+#ifdef RLIMIT_RTPRIO
+                       "r::"
 #endif
                        ;
 
@@ -340,7 +405,7 @@ static void printlim(unsigned opts, const struct rlimit *limit,
                val = limit->rlim_cur;
 
        if (val == RLIM_INFINITY)
-               printf("unlimited\n");
+               puts("unlimited");
        else {
                val >>= l->factor_shift;
                printf("%llu\n", (long long) val);
@@ -360,17 +425,9 @@ shell_builtin_ulimit(char **argv)
        /* In case getopt was already called:
         * reset the libc getopt() function, which keeps internal state.
         */
-#ifdef __GLIBC__
-       optind = 0;
-#else /* BSD style */
-       optind = 1;
-       /* optreset = 1; */
-#endif
-       /* optarg = NULL; opterr = 0; optopt = 0; - do we need this?? */
+       GETOPT_RESET();
 
-        argc = 1;
-        while (argv[argc])
-                argc++;
+       argc = string_array_len(argv);
 
        opts = 0;
        while (1) {
@@ -453,7 +510,6 @@ shell_builtin_ulimit(char **argv)
                        /* bad option. getopt already complained. */
                        break;
                }
-
        } /* while (there are options) */
 
        return 0;