blob: a9f8d84130d509a393ca40cf8f35457ec1fb4b4a [file] [log] [blame]
Denys Vlasenko73067272010-01-12 22:11:24 +01001/* 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 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +020017 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
Denys Vlasenko73067272010-01-12 22:11:24 +010018 */
19#include "libbb.h"
20#include "shell_common.h"
Mike Frysingerc5fe9f72012-07-05 23:19:09 -040021#include <sys/resource.h> /* getrlimit */
Denys Vlasenko73067272010-01-12 22:11:24 +010022
Denys Vlasenko73067272010-01-12 22:11:24 +010023const char defifsvar[] ALIGN1 = "IFS= \t\n";
Denys Vlasenkoe627ac92016-09-30 14:36:59 +020024const char defoptindvar[] ALIGN1 = "OPTIND=1";
Denys Vlasenko25d9b912010-01-13 18:22:35 +010025
26
27int FAST_FUNC is_well_formed_var_name(const char *s, char terminator)
28{
29 if (!s || !(isalpha(*s) || *s == '_'))
30 return 0;
31
32 do
33 s++;
34 while (isalnum(*s) || *s == '_');
35
36 return *s == terminator;
37}
Denys Vlasenko599ae1e2010-05-23 17:49:50 +020038
39/* read builtin */
40
Denys Vlasenko25ce3ee2013-07-14 01:23:06 +020041/* Needs to be interruptible: shell must handle traps and shell-special signals
Denys Vlasenko80542ba2011-05-08 21:23:43 +020042 * while inside read. To implement this, be sure to not loop on EINTR
43 * and return errno == EINTR reliably.
44 */
Denys Vlasenko599ae1e2010-05-23 17:49:50 +020045//TODO: use more efficient setvar() which takes a pointer to malloced "VAR=VAL"
46//string. hush naturally has it, and ash has setvareq().
47//Here we can simply store "VAR=" at buffer start and store read data directly
48//after "=", then pass buffer to setvar() to consume.
49const char* FAST_FUNC
50shell_builtin_read(void FAST_FUNC (*setvar)(const char *name, const char *val),
51 char **argv,
52 const char *ifs,
53 int read_flags,
54 const char *opt_n,
55 const char *opt_p,
56 const char *opt_t,
57 const char *opt_u
58)
59{
Denys Vlasenkoeae12682017-07-20 16:09:31 +020060 struct pollfd pfd[1];
61#define fd (pfd[0].fd) /* -u FD */
Denys Vlasenko80542ba2011-05-08 21:23:43 +020062 unsigned err;
Denys Vlasenko599ae1e2010-05-23 17:49:50 +020063 unsigned end_ms; /* -t TIMEOUT */
Denys Vlasenko599ae1e2010-05-23 17:49:50 +020064 int nchars; /* -n NUM */
65 char **pp;
66 char *buffer;
67 struct termios tty, old_tty;
68 const char *retval;
69 int bufpos; /* need to be able to hold -1 */
70 int startword;
71 smallint backslash;
72
Denys Vlasenko80542ba2011-05-08 21:23:43 +020073 errno = err = 0;
74
Denys Vlasenko599ae1e2010-05-23 17:49:50 +020075 pp = argv;
76 while (*pp) {
77 if (!is_well_formed_var_name(*pp, '\0')) {
78 /* Mimic bash message */
79 bb_error_msg("read: '%s': not a valid identifier", *pp);
80 return (const char *)(uintptr_t)1;
81 }
82 pp++;
83 }
84
85 nchars = 0; /* if != 0, -n is in effect */
86 if (opt_n) {
87 nchars = bb_strtou(opt_n, NULL, 10);
88 if (nchars < 0 || errno)
89 return "invalid count";
90 /* note: "-n 0": off (bash 3.2 does this too) */
91 }
Denys Vlasenkoeae12682017-07-20 16:09:31 +020092
Denys Vlasenko599ae1e2010-05-23 17:49:50 +020093 end_ms = 0;
Denys Vlasenkoeae12682017-07-20 16:09:31 +020094 if (opt_t && !ENABLE_FEATURE_SH_READ_FRAC) {
Denys Vlasenko599ae1e2010-05-23 17:49:50 +020095 end_ms = bb_strtou(opt_t, NULL, 10);
Denys Vlasenkoeae12682017-07-20 16:09:31 +020096 if (errno)
Denys Vlasenko599ae1e2010-05-23 17:49:50 +020097 return "invalid timeout";
Denys Vlasenkoeae12682017-07-20 16:09:31 +020098 if (end_ms > UINT_MAX / 2048) /* be safely away from overflow */
99 end_ms = UINT_MAX / 2048;
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200100 end_ms *= 1000;
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200101 }
Denys Vlasenkoeae12682017-07-20 16:09:31 +0200102 if (opt_t && ENABLE_FEATURE_SH_READ_FRAC) {
103 /* bash 4.3 (maybe earlier) supports -t N.NNNNNN */
104 char *p;
105 /* Eat up to three fractional digits */
106 int frac_digits = 3 + 1;
107
108 end_ms = bb_strtou(opt_t, &p, 10);
109 if (end_ms > UINT_MAX / 2048) /* be safely away from overflow */
110 end_ms = UINT_MAX / 2048;
111
112 if (errno) {
113 /* EINVAL = number is ok, but not NUL terminated */
114 if (errno != EINVAL || *p != '.')
115 return "invalid timeout";
116 /* Do not check the rest: bash allows "0.123456xyz" */
117 while (*++p && --frac_digits) {
118 end_ms *= 10;
119 end_ms += (*p - '0');
120 if ((unsigned char)(*p - '0') > 9)
121 return "invalid timeout";
122 }
123 }
124 while (--frac_digits > 0) {
125 end_ms *= 10;
126 }
127 }
128
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200129 fd = STDIN_FILENO;
130 if (opt_u) {
131 fd = bb_strtou(opt_u, NULL, 10);
132 if (fd < 0 || errno)
133 return "invalid file descriptor";
134 }
135
Denys Vlasenkoeae12682017-07-20 16:09:31 +0200136 if (opt_t && end_ms == 0) {
137 /* "If timeout is 0, read returns immediately, without trying
138 * to read any data. The exit status is 0 if input is available
139 * on the specified file descriptor, non-zero otherwise."
140 * bash seems to ignore -p PROMPT for this use case.
141 */
142 int r;
143 pfd[0].events = POLLIN;
144 r = poll(pfd, 1, /*timeout:*/ 0);
145 /* Return 0 only if poll returns 1 ("one fd ready"), else return 1: */
146 return (const char *)(uintptr_t)(r <= 0);
147 }
148
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200149 if (opt_p && isatty(fd)) {
150 fputs(opt_p, stderr);
151 fflush_all();
152 }
153
154 if (ifs == NULL)
155 ifs = defifs;
156
157 if (nchars || (read_flags & BUILTIN_READ_SILENT)) {
158 tcgetattr(fd, &tty);
159 old_tty = tty;
160 if (nchars) {
161 tty.c_lflag &= ~ICANON;
Denys Vlasenko7ce209b2012-01-15 22:58:06 +0100162 // Setting it to more than 1 breaks poll():
163 // it blocks even if there's data. !??
164 //tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
Denys Vlasenko01ccdd12017-01-11 16:17:59 +0100165 /* reads will block only if < 1 char is available */
Denys Vlasenko7ce209b2012-01-15 22:58:06 +0100166 tty.c_cc[VMIN] = 1;
167 /* no timeout (reads block forever) */
168 tty.c_cc[VTIME] = 0;
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200169 }
170 if (read_flags & BUILTIN_READ_SILENT) {
171 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
172 }
173 /* This forces execution of "restoring" tcgetattr later */
174 read_flags |= BUILTIN_READ_SILENT;
175 /* if tcgetattr failed, tcsetattr will fail too.
176 * Ignoring, it's harmless. */
177 tcsetattr(fd, TCSANOW, &tty);
178 }
179
180 retval = (const char *)(uintptr_t)0;
181 startword = 1;
182 backslash = 0;
Denys Vlasenkoeae12682017-07-20 16:09:31 +0200183 if (opt_t)
184 end_ms += (unsigned)monotonic_ms();
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200185 buffer = NULL;
186 bufpos = 0;
187 do {
188 char c;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200189 int timeout;
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200190
Denys Vlasenko10c01312011-05-11 11:49:21 +0200191 if ((bufpos & 0xff) == 0)
Denys Vlasenko9e71e3c2012-09-06 13:28:10 +0200192 buffer = xrealloc(buffer, bufpos + 0x101);
Denys Vlasenko80542ba2011-05-08 21:23:43 +0200193
Denys Vlasenko10c01312011-05-11 11:49:21 +0200194 timeout = -1;
Denys Vlasenkoeae12682017-07-20 16:09:31 +0200195 if (opt_t) {
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200196 timeout = end_ms - (unsigned)monotonic_ms();
Denys Vlasenkoeae12682017-07-20 16:09:31 +0200197 /* ^^^^^^^^^^^^^ all values are unsigned,
198 * wrapping math is used here, good even if
199 * 32-bit unix time wrapped (year 2038+).
200 */
Denys Vlasenko10c01312011-05-11 11:49:21 +0200201 if (timeout <= 0) { /* already late? */
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200202 retval = (const char *)(uintptr_t)1;
203 goto ret;
204 }
205 }
206
Denys Vlasenko10c01312011-05-11 11:49:21 +0200207 /* We must poll even if timeout is -1:
208 * we want to be interrupted if signal arrives,
209 * regardless of SA_RESTART-ness of that signal!
210 */
211 errno = 0;
Denys Vlasenko10c01312011-05-11 11:49:21 +0200212 pfd[0].events = POLLIN;
Denys Vlasenkoeae12682017-07-20 16:09:31 +0200213 if (poll(pfd, 1, timeout) <= 0) {
Denys Vlasenko10c01312011-05-11 11:49:21 +0200214 /* timed out, or EINTR */
215 err = errno;
216 retval = (const char *)(uintptr_t)1;
217 goto ret;
218 }
219 if (read(fd, &buffer[bufpos], 1) != 1) {
Denys Vlasenko80542ba2011-05-08 21:23:43 +0200220 err = errno;
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200221 retval = (const char *)(uintptr_t)1;
222 break;
223 }
Denys Vlasenko10c01312011-05-11 11:49:21 +0200224
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200225 c = buffer[bufpos];
226 if (c == '\0')
227 continue;
Denys Vlasenkof5470412017-05-22 19:34:45 +0200228 if (!(read_flags & BUILTIN_READ_RAW)) {
229 if (backslash) {
230 backslash = 0;
231 if (c != '\n')
232 goto put;
233 continue;
234 }
235 if (c == '\\') {
236 backslash = 1;
237 continue;
238 }
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200239 }
240 if (c == '\n')
241 break;
242
243 /* $IFS splitting. NOT done if we run "read"
244 * without variable names (bash compat).
245 * Thus, "read" and "read REPLY" are not the same.
246 */
247 if (argv[0]) {
248/* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
249 const char *is_ifs = strchr(ifs, c);
250 if (startword && is_ifs) {
251 if (isspace(c))
252 continue;
253 /* it is a non-space ifs char */
254 startword--;
255 if (startword == 1) /* first one? */
256 continue; /* yes, it is not next word yet */
257 }
258 startword = 0;
259 if (argv[1] != NULL && is_ifs) {
260 buffer[bufpos] = '\0';
261 bufpos = 0;
262 setvar(*argv, buffer);
263 argv++;
264 /* can we skip one non-space ifs char? (2: yes) */
265 startword = isspace(c) ? 2 : 1;
266 continue;
267 }
268 }
269 put:
270 bufpos++;
271 } while (--nchars);
272
273 if (argv[0]) {
274 /* Remove trailing space $IFS chars */
275 while (--bufpos >= 0 && isspace(buffer[bufpos]) && strchr(ifs, buffer[bufpos]) != NULL)
276 continue;
277 buffer[bufpos + 1] = '\0';
278 /* Use the remainder as a value for the next variable */
279 setvar(*argv, buffer);
280 /* Set the rest to "" */
281 while (*++argv)
282 setvar(*argv, "");
283 } else {
284 /* Note: no $IFS removal */
285 buffer[bufpos] = '\0';
286 setvar("REPLY", buffer);
287 }
288
289 ret:
290 free(buffer);
291 if (read_flags & BUILTIN_READ_SILENT)
292 tcsetattr(fd, TCSANOW, &old_tty);
Denys Vlasenko80542ba2011-05-08 21:23:43 +0200293
294 errno = err;
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200295 return retval;
Denys Vlasenkoeae12682017-07-20 16:09:31 +0200296#undef fd
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200297}
298
299/* ulimit builtin */
300
301struct limits {
302 uint8_t cmd; /* RLIMIT_xxx fit into it */
303 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
304 char option;
305 const char *name;
306};
307
308static const struct limits limits_tbl[] = {
309#ifdef RLIMIT_FSIZE
310 { RLIMIT_FSIZE, 9, 'f', "file size (blocks)" },
311#endif
312#ifdef RLIMIT_CPU
313 { RLIMIT_CPU, 0, 't', "cpu time (seconds)" },
314#endif
315#ifdef RLIMIT_DATA
316 { RLIMIT_DATA, 10, 'd', "data seg size (kb)" },
317#endif
318#ifdef RLIMIT_STACK
319 { RLIMIT_STACK, 10, 's', "stack size (kb)" },
320#endif
321#ifdef RLIMIT_CORE
322 { RLIMIT_CORE, 9, 'c', "core file size (blocks)" },
323#endif
324#ifdef RLIMIT_RSS
325 { RLIMIT_RSS, 10, 'm', "resident set size (kb)" },
326#endif
327#ifdef RLIMIT_MEMLOCK
328 { RLIMIT_MEMLOCK, 10, 'l', "locked memory (kb)" },
329#endif
330#ifdef RLIMIT_NPROC
331 { RLIMIT_NPROC, 0, 'p', "processes" },
332#endif
333#ifdef RLIMIT_NOFILE
334 { RLIMIT_NOFILE, 0, 'n', "file descriptors" },
335#endif
336#ifdef RLIMIT_AS
337 { RLIMIT_AS, 10, 'v', "address space (kb)" },
338#endif
339#ifdef RLIMIT_LOCKS
340 { RLIMIT_LOCKS, 0, 'w', "locks" },
341#endif
Denys Vlasenkoe32d05b2011-04-04 02:12:14 +0200342#ifdef RLIMIT_NICE
343 { RLIMIT_NICE, 0, 'e', "scheduling priority" },
344#endif
345#ifdef RLIMIT_RTPRIO
346 { RLIMIT_RTPRIO, 0, 'r', "real-time priority" },
347#endif
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200348};
349
350enum {
351 OPT_hard = (1 << 0),
352 OPT_soft = (1 << 1),
353};
354
355/* "-": treat args as parameters of option with ASCII code 1 */
Denys Vlasenko3e134eb2016-04-22 18:09:21 +0200356static const char ulimit_opt_string[] ALIGN1 = "-HSa"
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200357#ifdef RLIMIT_FSIZE
358 "f::"
359#endif
360#ifdef RLIMIT_CPU
361 "t::"
362#endif
363#ifdef RLIMIT_DATA
364 "d::"
365#endif
366#ifdef RLIMIT_STACK
367 "s::"
368#endif
369#ifdef RLIMIT_CORE
370 "c::"
371#endif
372#ifdef RLIMIT_RSS
373 "m::"
374#endif
375#ifdef RLIMIT_MEMLOCK
376 "l::"
377#endif
378#ifdef RLIMIT_NPROC
379 "p::"
380#endif
381#ifdef RLIMIT_NOFILE
382 "n::"
383#endif
384#ifdef RLIMIT_AS
385 "v::"
386#endif
387#ifdef RLIMIT_LOCKS
388 "w::"
389#endif
Denys Vlasenkoe32d05b2011-04-04 02:12:14 +0200390#ifdef RLIMIT_NICE
391 "e::"
392#endif
393#ifdef RLIMIT_RTPRIO
394 "r::"
395#endif
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200396 ;
397
398static void printlim(unsigned opts, const struct rlimit *limit,
399 const struct limits *l)
400{
401 rlim_t val;
402
403 val = limit->rlim_max;
404 if (!(opts & OPT_hard))
405 val = limit->rlim_cur;
406
407 if (val == RLIM_INFINITY)
Denys Vlasenkod60752f2015-10-07 22:42:45 +0200408 puts("unlimited");
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200409 else {
410 val >>= l->factor_shift;
411 printf("%llu\n", (long long) val);
412 }
413}
414
415int FAST_FUNC
416shell_builtin_ulimit(char **argv)
417{
418 unsigned opts;
419 unsigned argc;
420
421 /* We can't use getopt32: need to handle commands like
422 * ulimit 123 -c2 -l 456
423 */
424
425 /* In case getopt was already called:
426 * reset the libc getopt() function, which keeps internal state.
427 */
Kaarle Ritvanen835ad3a2017-04-12 00:58:46 +0300428 GETOPT_RESET();
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200429
Denys Vlasenkod4e4fdb2017-07-03 21:31:16 +0200430 argc = string_array_len(argv);
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200431
432 opts = 0;
433 while (1) {
434 struct rlimit limit;
435 const struct limits *l;
436 int opt_char = getopt(argc, argv, ulimit_opt_string);
437
438 if (opt_char == -1)
439 break;
440 if (opt_char == 'H') {
441 opts |= OPT_hard;
442 continue;
443 }
444 if (opt_char == 'S') {
445 opts |= OPT_soft;
446 continue;
447 }
448
449 if (opt_char == 'a') {
450 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
451 getrlimit(l->cmd, &limit);
452 printf("-%c: %-30s ", l->option, l->name);
453 printlim(opts, &limit, l);
454 }
455 continue;
456 }
457
458 if (opt_char == 1)
459 opt_char = 'f';
460 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
461 if (opt_char == l->option) {
462 char *val_str;
463
464 getrlimit(l->cmd, &limit);
465
466 val_str = optarg;
467 if (!val_str && argv[optind] && argv[optind][0] != '-')
468 val_str = argv[optind++]; /* ++ skips NN in "-c NN" case */
469 if (val_str) {
470 rlim_t val;
471
472 if (strcmp(val_str, "unlimited") == 0)
473 val = RLIM_INFINITY;
474 else {
475 if (sizeof(val) == sizeof(int))
476 val = bb_strtou(val_str, NULL, 10);
477 else if (sizeof(val) == sizeof(long))
478 val = bb_strtoul(val_str, NULL, 10);
479 else
480 val = bb_strtoull(val_str, NULL, 10);
481 if (errno) {
Denys Vlasenkob32a5432010-08-29 13:29:02 +0200482 bb_error_msg("invalid number '%s'", val_str);
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200483 return EXIT_FAILURE;
484 }
485 val <<= l->factor_shift;
486 }
487//bb_error_msg("opt %c val_str:'%s' val:%lld", opt_char, val_str, (long long)val);
Alexander Shishkin17e0e432010-07-27 08:40:55 +0200488 /* from man bash: "If neither -H nor -S
489 * is specified, both the soft and hard
490 * limits are set. */
491 if (!opts)
492 opts = OPT_hard + OPT_soft;
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200493 if (opts & OPT_hard)
494 limit.rlim_max = val;
Alexander Shishkin17e0e432010-07-27 08:40:55 +0200495 if (opts & OPT_soft)
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200496 limit.rlim_cur = val;
497//bb_error_msg("setrlimit(%d, %lld, %lld)", l->cmd, (long long)limit.rlim_cur, (long long)limit.rlim_max);
498 if (setrlimit(l->cmd, &limit) < 0) {
499 bb_perror_msg("error setting limit");
500 return EXIT_FAILURE;
501 }
502 } else {
503 printlim(opts, &limit, l);
504 }
505 break;
506 }
507 } /* for (every possible opt) */
508
509 if (l == &limits_tbl[ARRAY_SIZE(limits_tbl)]) {
510 /* bad option. getopt already complained. */
511 break;
512 }
Denys Vlasenko599ae1e2010-05-23 17:49:50 +0200513 } /* while (there are options) */
514
515 return 0;
516}