ash,hush: fix ulimit to be more bash-compat, closes 11791
[oweals/busybox.git] / shell / shell_common.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Adapted from ash applet code
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Copyright (c) 1989, 1991, 1993, 1994
9  *      The Regents of the University of California.  All rights reserved.
10  *
11  * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
12  * was re-ported from NetBSD and debianized.
13  *
14  * Copyright (c) 2010 Denys Vlasenko
15  * Split from ash.c
16  *
17  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
18  */
19 #include "libbb.h"
20 #include "shell_common.h"
21
22 const char defifsvar[] ALIGN1 = "IFS= \t\n";
23 const char defoptindvar[] ALIGN1 = "OPTIND=1";
24
25
26 int FAST_FUNC is_well_formed_var_name(const char *s, char terminator)
27 {
28         if (!s || !(isalpha(*s) || *s == '_'))
29                 return 0;
30
31         do
32                 s++;
33         while (isalnum(*s) || *s == '_');
34
35         return *s == terminator;
36 }
37
38 /* read builtin */
39
40 /* Needs to be interruptible: shell must handle traps and shell-special signals
41  * while inside read. To implement this, be sure to not loop on EINTR
42  * and return errno == EINTR reliably.
43  */
44 //TODO: use more efficient setvar() which takes a pointer to malloced "VAR=VAL"
45 //string. hush naturally has it, and ash has setvareq().
46 //Here we can simply store "VAR=" at buffer start and store read data directly
47 //after "=", then pass buffer to setvar() to consume.
48 const char* FAST_FUNC
49 shell_builtin_read(struct builtin_read_params *params)
50 {
51         struct pollfd pfd[1];
52 #define fd (pfd[0].fd) /* -u FD */
53         unsigned err;
54         unsigned end_ms; /* -t TIMEOUT */
55         int nchars; /* -n NUM */
56         char **pp;
57         char *buffer;
58         char delim;
59         struct termios tty, old_tty;
60         const char *retval;
61         int bufpos; /* need to be able to hold -1 */
62         int startword;
63         smallint backslash;
64         char **argv;
65         const char *ifs;
66         int read_flags;
67
68         errno = err = 0;
69
70         argv = params->argv;
71         pp = argv;
72         while (*pp) {
73                 if (!is_well_formed_var_name(*pp, '\0')) {
74                         /* Mimic bash message */
75                         bb_error_msg("read: '%s': not a valid identifier", *pp);
76                         return (const char *)(uintptr_t)1;
77                 }
78                 pp++;
79         }
80
81         nchars = 0; /* if != 0, -n is in effect */
82         if (params->opt_n) {
83                 nchars = bb_strtou(params->opt_n, NULL, 10);
84                 if (nchars < 0 || errno)
85                         return "invalid count";
86                 /* note: "-n 0": off (bash 3.2 does this too) */
87         }
88
89         end_ms = 0;
90         if (params->opt_t && !ENABLE_FEATURE_SH_READ_FRAC) {
91                 end_ms = bb_strtou(params->opt_t, NULL, 10);
92                 if (errno)
93                         return "invalid timeout";
94                 if (end_ms > UINT_MAX / 2048) /* be safely away from overflow */
95                         end_ms = UINT_MAX / 2048;
96                 end_ms *= 1000;
97         }
98         if (params->opt_t && ENABLE_FEATURE_SH_READ_FRAC) {
99                 /* bash 4.3 (maybe earlier) supports -t N.NNNNNN */
100                 char *p;
101                 /* Eat up to three fractional digits */
102                 int frac_digits = 3 + 1;
103
104                 end_ms = bb_strtou(params->opt_t, &p, 10);
105                 if (end_ms > UINT_MAX / 2048) /* be safely away from overflow */
106                         end_ms = UINT_MAX / 2048;
107
108                 if (errno) {
109                         /* EINVAL = number is ok, but not NUL terminated */
110                         if (errno != EINVAL || *p != '.')
111                                 return "invalid timeout";
112                         /* Do not check the rest: bash allows "0.123456xyz" */
113                         while (*++p && --frac_digits) {
114                                 end_ms *= 10;
115                                 end_ms += (*p - '0');
116                                 if ((unsigned char)(*p - '0') > 9)
117                                         return "invalid timeout";
118                         }
119                 }
120                 while (--frac_digits > 0) {
121                         end_ms *= 10;
122                 }
123         }
124
125         fd = STDIN_FILENO;
126         if (params->opt_u) {
127                 fd = bb_strtou(params->opt_u, NULL, 10);
128                 if (fd < 0 || errno)
129                         return "invalid file descriptor";
130         }
131
132         if (params->opt_t && end_ms == 0) {
133                 /* "If timeout is 0, read returns immediately, without trying
134                  * to read any data. The exit status is 0 if input is available
135                  * on the specified file descriptor, non-zero otherwise."
136                  * bash seems to ignore -p PROMPT for this use case.
137                  */
138                 int r;
139                 pfd[0].events = POLLIN;
140                 r = poll(pfd, 1, /*timeout:*/ 0);
141                 /* Return 0 only if poll returns 1 ("one fd ready"), else return 1: */
142                 return (const char *)(uintptr_t)(r <= 0);
143         }
144
145         if (params->opt_p && isatty(fd)) {
146                 fputs(params->opt_p, stderr);
147                 fflush_all();
148         }
149
150         ifs = params->ifs;
151         if (ifs == NULL)
152                 ifs = defifs;
153
154         read_flags = params->read_flags;
155         if (nchars || (read_flags & BUILTIN_READ_SILENT)) {
156                 tcgetattr(fd, &tty);
157                 old_tty = tty;
158                 if (nchars) {
159                         tty.c_lflag &= ~ICANON;
160                         // Setting it to more than 1 breaks poll():
161                         // it blocks even if there's data. !??
162                         //tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
163                         /* reads will block only if < 1 char is available */
164                         tty.c_cc[VMIN] = 1;
165                         /* no timeout (reads block forever) */
166                         tty.c_cc[VTIME] = 0;
167                 }
168                 if (read_flags & BUILTIN_READ_SILENT) {
169                         tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
170                 }
171                 /* This forces execution of "restoring" tcgetattr later */
172                 read_flags |= BUILTIN_READ_SILENT;
173                 /* if tcgetattr failed, tcsetattr will fail too.
174                  * Ignoring, it's harmless. */
175                 tcsetattr(fd, TCSANOW, &tty);
176         }
177
178         retval = (const char *)(uintptr_t)0;
179         startword = 1;
180         backslash = 0;
181         if (params->opt_t)
182                 end_ms += (unsigned)monotonic_ms();
183         buffer = NULL;
184         bufpos = 0;
185         delim = params->opt_d ? params->opt_d[0] : '\n';
186         do {
187                 char c;
188                 int timeout;
189
190                 if ((bufpos & 0xff) == 0)
191                         buffer = xrealloc(buffer, bufpos + 0x101);
192
193                 timeout = -1;
194                 if (params->opt_t) {
195                         timeout = end_ms - (unsigned)monotonic_ms();
196                         /* ^^^^^^^^^^^^^ all values are unsigned,
197                          * wrapping math is used here, good even if
198                          * 32-bit unix time wrapped (year 2038+).
199                          */
200                         if (timeout <= 0) { /* already late? */
201                                 retval = (const char *)(uintptr_t)1;
202                                 goto ret;
203                         }
204                 }
205
206                 /* We must poll even if timeout is -1:
207                  * we want to be interrupted if signal arrives,
208                  * regardless of SA_RESTART-ness of that signal!
209                  */
210                 errno = 0;
211                 pfd[0].events = POLLIN;
212                 if (poll(pfd, 1, timeout) <= 0) {
213                         /* timed out, or EINTR */
214                         err = errno;
215                         retval = (const char *)(uintptr_t)1;
216                         goto ret;
217                 }
218                 if (read(fd, &buffer[bufpos], 1) != 1) {
219                         err = errno;
220                         retval = (const char *)(uintptr_t)1;
221                         break;
222                 }
223
224                 c = buffer[bufpos];
225                 if (c == '\0')
226                         continue;
227                 if (!(read_flags & BUILTIN_READ_RAW)) {
228                         if (backslash) {
229                                 backslash = 0;
230                                 if (c != '\n')
231                                         goto put;
232                                 continue;
233                         }
234                         if (c == '\\') {
235                                 backslash = 1;
236                                 continue;
237                         }
238                 }
239                 if (c == delim) /* '\n' or -d CHAR */
240                         break;
241
242                 /* $IFS splitting. NOT done if we run "read"
243                  * without variable names (bash compat).
244                  * Thus, "read" and "read REPLY" are not the same.
245                  */
246                 if (!params->opt_d && argv[0]) {
247 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
248                         const char *is_ifs = strchr(ifs, c);
249                         if (startword && is_ifs) {
250                                 if (isspace(c))
251                                         continue;
252                                 /* it is a non-space ifs char */
253                                 startword--;
254                                 if (startword == 1) /* first one? */
255                                         continue; /* yes, it is not next word yet */
256                         }
257                         startword = 0;
258                         if (argv[1] != NULL && is_ifs) {
259                                 buffer[bufpos] = '\0';
260                                 bufpos = 0;
261                                 params->setvar(*argv, buffer);
262                                 argv++;
263                                 /* can we skip one non-space ifs char? (2: yes) */
264                                 startword = isspace(c) ? 2 : 1;
265                                 continue;
266                         }
267                 }
268  put:
269                 bufpos++;
270         } while (--nchars);
271
272         if (argv[0]) {
273                 /* Remove trailing space $IFS chars */
274                 while (--bufpos >= 0
275                  && isspace(buffer[bufpos])
276                  && strchr(ifs, buffer[bufpos]) != NULL
277                 ) {
278                         continue;
279                 }
280                 buffer[bufpos + 1] = '\0';
281
282                 /* Last variable takes the entire remainder with delimiters
283                  * (sans trailing whitespace $IFS),
284                  * but ***only "if there are fewer vars than fields"(c)***!
285                  * The "X:Y:" case below: there are two fields,
286                  * and therefore last delimiter (:) is eaten:
287                  * IFS=": "
288                  * echo "X:Y:Z:"  | (read x y; echo "|$x|$y|") # |X|Y:Z:|
289                  * echo "X:Y:Z"   | (read x y; echo "|$x|$y|") # |X|Y:Z|
290                  * echo "X:Y:"    | (read x y; echo "|$x|$y|") # |X|Y|, not |X|Y:|
291                  * echo "X:Y  : " | (read x y; echo "|$x|$y|") # |X|Y|
292                  */
293                 if (bufpos >= 0
294                  && strchr(ifs, buffer[bufpos]) != NULL
295                 ) {
296                         /* There _is_ a non-whitespace IFS char */
297                         /* Skip whitespace IFS char before it */
298                         while (--bufpos >= 0
299                          && isspace(buffer[bufpos])
300                          && strchr(ifs, buffer[bufpos]) != NULL
301                         ) {
302                                 continue;
303                         }
304                         /* Are there $IFS chars? */
305                         if (strcspn(buffer, ifs) >= ++bufpos) {
306                                 /* No: last var takes one field, not more */
307                                 /* So, drop trailing IFS delims */
308                                 buffer[bufpos] = '\0';
309                         }
310                 }
311
312                 /* Use the remainder as a value for the next variable */
313                 params->setvar(*argv, buffer);
314                 /* Set the rest to "" */
315                 while (*++argv)
316                         params->setvar(*argv, "");
317         } else {
318                 /* Note: no $IFS removal */
319                 buffer[bufpos] = '\0';
320                 params->setvar("REPLY", buffer);
321         }
322
323  ret:
324         free(buffer);
325         if (read_flags & BUILTIN_READ_SILENT)
326                 tcsetattr(fd, TCSANOW, &old_tty);
327
328         errno = err;
329         return retval;
330 #undef fd
331 }
332
333 /* ulimit builtin */
334
335 struct limits {
336         uint8_t cmd;            /* RLIMIT_xxx fit into it */
337         uint8_t factor_shift;   /* shift by to get rlim_{cur,max} values */
338         const char *name;
339 };
340
341 static const struct limits limits_tbl[] = {
342 /* No RLIMIT_FSIZE define guard since -f is the default limit and this must exist */
343         { RLIMIT_FSIZE,         9,      "file size (blocks)" },      // -f
344 #ifdef RLIMIT_CPU
345         { RLIMIT_CPU,           0,      "cpu time (seconds)" },      // -t
346 #endif
347 #ifdef RLIMIT_DATA
348         { RLIMIT_DATA,          10,     "data seg size (kb)" },      // -d
349 #endif
350 #ifdef RLIMIT_STACK
351         { RLIMIT_STACK,         10,     "stack size (kb)" },         // -s
352 #endif
353 #ifdef RLIMIT_CORE
354         { RLIMIT_CORE,          9,      "core file size (blocks)" }, // -c
355 #endif
356 #ifdef RLIMIT_RSS
357         { RLIMIT_RSS,           10,     "resident set size (kb)" },  // -m
358 #endif
359 #ifdef RLIMIT_MEMLOCK
360         { RLIMIT_MEMLOCK,       10,     "locked memory (kb)" },      // -l
361 #endif
362 #ifdef RLIMIT_NPROC
363         { RLIMIT_NPROC,         0,      "processes" },               // -p
364 #endif
365 #ifdef RLIMIT_NOFILE
366         { RLIMIT_NOFILE,        0,      "file descriptors" },        // -n
367 #endif
368 #ifdef RLIMIT_AS
369         { RLIMIT_AS,            10,     "address space (kb)" },      // -v
370 #endif
371 #ifdef RLIMIT_LOCKS
372         { RLIMIT_LOCKS,         0,      "locks" },                   // -w
373 #endif
374 #ifdef RLIMIT_NICE
375         { RLIMIT_NICE,          0,      "scheduling priority" },     // -e
376 #endif
377 #ifdef RLIMIT_RTPRIO
378         { RLIMIT_RTPRIO,        0,      "real-time priority" },      // -r
379 #endif
380 };
381
382 static const char limit_chars[] ALIGN1 =
383                         "f"
384 #ifdef RLIMIT_CPU
385                         "t"
386 #endif
387 #ifdef RLIMIT_DATA
388                         "d"
389 #endif
390 #ifdef RLIMIT_STACK
391                         "s"
392 #endif
393 #ifdef RLIMIT_CORE
394                         "c"
395 #endif
396 #ifdef RLIMIT_RSS
397                         "m"
398 #endif
399 #ifdef RLIMIT_MEMLOCK
400                         "l"
401 #endif
402 #ifdef RLIMIT_NPROC
403                         "p"
404 #endif
405 #ifdef RLIMIT_NOFILE
406                         "n"
407 #endif
408 #ifdef RLIMIT_AS
409                         "v"
410 #endif
411 #ifdef RLIMIT_LOCKS
412                         "w"
413 #endif
414 #ifdef RLIMIT_NICE
415                         "e"
416 #endif
417 #ifdef RLIMIT_RTPRIO
418                         "r"
419 #endif
420 ;
421
422 /* "-": treat args as parameters of option with ASCII code 1 */
423 static const char ulimit_opt_string[] ALIGN1 = "-HSa"
424                         "f::"
425 #ifdef RLIMIT_CPU
426                         "t::"
427 #endif
428 #ifdef RLIMIT_DATA
429                         "d::"
430 #endif
431 #ifdef RLIMIT_STACK
432                         "s::"
433 #endif
434 #ifdef RLIMIT_CORE
435                         "c::"
436 #endif
437 #ifdef RLIMIT_RSS
438                         "m::"
439 #endif
440 #ifdef RLIMIT_MEMLOCK
441                         "l::"
442 #endif
443 #ifdef RLIMIT_NPROC
444                         "p::"
445 #endif
446 #ifdef RLIMIT_NOFILE
447                         "n::"
448 #endif
449 #ifdef RLIMIT_AS
450                         "v::"
451 #endif
452 #ifdef RLIMIT_LOCKS
453                         "w::"
454 #endif
455 #ifdef RLIMIT_NICE
456                         "e::"
457 #endif
458 #ifdef RLIMIT_RTPRIO
459                         "r::"
460 #endif
461                         ;
462
463 enum {
464         OPT_hard = (1 << 0),
465         OPT_soft = (1 << 1),
466         OPT_all  = (1 << 2),
467 };
468
469 static void printlim(unsigned opts, const struct rlimit *limit,
470                         const struct limits *l)
471 {
472         rlim_t val;
473
474         val = limit->rlim_max;
475         if (opts & OPT_soft)
476                 val = limit->rlim_cur;
477
478         if (val == RLIM_INFINITY)
479                 puts("unlimited");
480         else {
481                 val >>= l->factor_shift;
482                 printf("%llu\n", (long long) val);
483         }
484 }
485
486 int FAST_FUNC
487 shell_builtin_ulimit(char **argv)
488 {
489         struct rlimit limit;
490         unsigned opt_cnt;
491         unsigned opts;
492         unsigned argc;
493         unsigned i;
494
495         /* We can't use getopt32: need to handle commands like
496          * ulimit 123 -c2 -l 456
497          */
498
499         /* In case getopt() was already called:
500          * reset libc getopt() internal state.
501          */
502         GETOPT_RESET();
503
504 // bash 4.4.23:
505 //
506 // -H and/or -S change meaning even of options *before* them: ulimit -f 2000 -H
507 // sets hard limit, ulimit -a -H prints hard limits.
508 //
509 // -a is equivalent for requesting all limits to be shown.
510 //
511 // If -a is specified, attempts to set limits are ignored:
512 //  ulimit -m 1000; ulimit -m 2000 -a
513 // shows 1000, not 2000. HOWEVER, *implicit* -f form "ulimit 2000 -a"
514 // DOES set -f limit [we don't implement this quirk], "ulimit -a 2000" does not.
515 // Options are still parsed: ulimit -az complains about unknown -z opt.
516 //
517 // -a is not cumulative: "ulimit -a -a" = "ulimit -a -f -m" = "ulimit -a"
518 //
519 // -HSa can be combined in one argument and with one other option (example: -Sm),
520 // but other options can't: limit value is an optional argument,
521 // thus "-mf" means "-m f", f is the parameter of -m.
522 //
523 // Limit can be set and then printed: ulimit -m 2000 -m
524 // If set more than once, they are set and printed in order:
525 // try ulimit -m -m 1000 -m -m 2000 -m -m 3000 -m
526 //
527 // Limits are shown in the order of options given:
528 // ulimit -m -f is not the same as ulimit -f -m.
529 //
530 // If both -S and -H are given, show soft limit.
531 //
532 // Short printout (limit value only) is printed only if just one option
533 // is given: ulimit -m. ulimit -f -m prints verbose lines.
534 // ulimit -f -f prints same verbose line twice.
535 // ulimit -m 10000 -f prints verbose line for -f.
536
537         argc = string_array_len(argv);
538
539         /* First pass over options: detect -H/-S/-a status,
540          * and "bare ulimit" and "only one option" cases
541          * by counting other opts.
542          */
543         opt_cnt = 0;
544         opts = 0;
545         while (1) {
546                 int opt_char = getopt(argc, argv, ulimit_opt_string);
547
548                 if (opt_char == -1)
549                         break;
550                 if (opt_char == 'H') {
551                         opts |= OPT_hard;
552                         continue;
553                 }
554                 if (opt_char == 'S') {
555                         opts |= OPT_soft;
556                         continue;
557                 }
558                 if (opt_char == 'a') {
559                         opts |= OPT_all;
560                         continue;
561                 }
562                 if (opt_char == '?') {
563                         /* bad option. getopt already complained. */
564                         return EXIT_FAILURE;
565                 }
566                 opt_cnt++;
567         } /* while (there are options) */
568
569         if (!(opts & (OPT_hard | OPT_soft)))
570                 opts |= (OPT_hard | OPT_soft);
571         if (opts & OPT_all) {
572                 for (i = 0; i < ARRAY_SIZE(limits_tbl); i++) {
573                         getrlimit(limits_tbl[i].cmd, &limit);
574                         printf("-%c: %-30s ", limit_chars[i], limits_tbl[i].name);
575                         printlim(opts, &limit, &limits_tbl[i]);
576                 }
577                 return EXIT_SUCCESS;
578         }
579
580         /* Second pass: set or print limits, in order */
581         GETOPT_RESET();
582         while (1) {
583                 char *val_str;
584                 int opt_char = getopt(argc, argv, ulimit_opt_string);
585
586                 if (opt_char == -1)
587                         break;
588                 if (opt_char == 'H')
589                         continue;
590                 if (opt_char == 'S')
591                         continue;
592                 //if (opt_char == 'a') - impossible
593
594                 i = 0; /* if "ulimit NNN", -f is assumed */
595                 if (opt_char != 1) {
596                         i = strchrnul(limit_chars, opt_char) - limit_chars;
597                         //if (i >= ARRAY_SIZE(limits_tbl)) - bad option, impossible
598                 }
599
600                 val_str = optarg;
601                 if (!val_str && argv[optind] && argv[optind][0] != '-')
602                         val_str = argv[optind++]; /* ++ skips NN in "-c NN" case */
603
604                 getrlimit(limits_tbl[i].cmd, &limit);
605                 if (!val_str) {
606                         if (opt_cnt > 1)
607                                 printf("-%c: %-30s ", limit_chars[i], limits_tbl[i].name);
608                         printlim(opts, &limit, &limits_tbl[i]);
609                 } else {
610                         rlim_t val = RLIM_INFINITY;
611                         if (strcmp(val_str, "unlimited") != 0) {
612                                 if (sizeof(val) == sizeof(int))
613                                         val = bb_strtou(val_str, NULL, 10);
614                                 else if (sizeof(val) == sizeof(long))
615                                         val = bb_strtoul(val_str, NULL, 10);
616                                 else
617                                         val = bb_strtoull(val_str, NULL, 10);
618                                 if (errno) {
619                                         bb_error_msg("invalid number '%s'", val_str);
620                                         return EXIT_FAILURE;
621                                 }
622                                 val <<= limits_tbl[i].factor_shift;
623                         }
624 //bb_error_msg("opt %c val_str:'%s' val:%lld", opt_char, val_str, (long long)val);
625                         /* from man bash: "If neither -H nor -S
626                          * is specified, both the soft and hard
627                          * limits are set. */
628                         if (opts & OPT_hard)
629                                 limit.rlim_max = val;
630                         if (opts & OPT_soft)
631                                 limit.rlim_cur = val;
632 //bb_error_msg("setrlimit(%d, %lld, %lld)", limits_tbl[i].cmd, (long long)limit.rlim_cur, (long long)limit.rlim_max);
633                         if (setrlimit(limits_tbl[i].cmd, &limit) < 0) {
634                                 bb_perror_msg("error setting limit");
635                                 return EXIT_FAILURE;
636                         }
637                 }
638         } /* while (there are options) */
639
640         if (opt_cnt == 0) {
641                 /* "bare ulimit": treat it as if it was -f */
642                 getrlimit(limits_tbl[0].cmd, &limit);
643                 printlim(opts, &limit, &limits_tbl[0]);
644         }
645
646         return EXIT_SUCCESS;
647 }