hush: fix handling of empty heredoc EOF marker
[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 #include <sys/resource.h> /* getrlimit */
22
23 const char defifsvar[] ALIGN1 = "IFS= \t\n";
24 const char defoptindvar[] ALIGN1 = "OPTIND=1";
25
26
27 int 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 }
38
39 /* read builtin */
40
41 /* Needs to be interruptible: shell must handle traps and shell-special signals
42  * while inside read. To implement this, be sure to not loop on EINTR
43  * and return errno == EINTR reliably.
44  */
45 //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.
49 const char* FAST_FUNC
50 shell_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 {
60         struct pollfd pfd[1];
61 #define fd (pfd[0].fd) /* -u FD */
62         unsigned err;
63         unsigned end_ms; /* -t TIMEOUT */
64         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
73         errno = err = 0;
74
75         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         }
92
93         end_ms = 0;
94         if (opt_t && !ENABLE_FEATURE_SH_READ_FRAC) {
95                 end_ms = bb_strtou(opt_t, NULL, 10);
96                 if (errno)
97                         return "invalid timeout";
98                 if (end_ms > UINT_MAX / 2048) /* be safely away from overflow */
99                         end_ms = UINT_MAX / 2048;
100                 end_ms *= 1000;
101         }
102         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
129         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
136         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
149         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;
162                         // 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;
165                         /* reads will block only if < 1 char is available */
166                         tty.c_cc[VMIN] = 1;
167                         /* no timeout (reads block forever) */
168                         tty.c_cc[VTIME] = 0;
169                 }
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;
183         if (opt_t)
184                 end_ms += (unsigned)monotonic_ms();
185         buffer = NULL;
186         bufpos = 0;
187         do {
188                 char c;
189                 int timeout;
190
191                 if ((bufpos & 0xff) == 0)
192                         buffer = xrealloc(buffer, bufpos + 0x101);
193
194                 timeout = -1;
195                 if (opt_t) {
196                         timeout = end_ms - (unsigned)monotonic_ms();
197                         /* ^^^^^^^^^^^^^ all values are unsigned,
198                          * wrapping math is used here, good even if
199                          * 32-bit unix time wrapped (year 2038+).
200                          */
201                         if (timeout <= 0) { /* already late? */
202                                 retval = (const char *)(uintptr_t)1;
203                                 goto ret;
204                         }
205                 }
206
207                 /* 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;
212                 pfd[0].events = POLLIN;
213                 if (poll(pfd, 1, timeout) <= 0) {
214                         /* 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) {
220                         err = errno;
221                         retval = (const char *)(uintptr_t)1;
222                         break;
223                 }
224
225                 c = buffer[bufpos];
226                 if (c == '\0')
227                         continue;
228                 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                         }
239                 }
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);
293
294         errno = err;
295         return retval;
296 #undef fd
297 }
298
299 /* ulimit builtin */
300
301 struct 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
308 static 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
342 #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
348 };
349
350 enum {
351         OPT_hard = (1 << 0),
352         OPT_soft = (1 << 1),
353 };
354
355 /* "-": treat args as parameters of option with ASCII code 1 */
356 static const char ulimit_opt_string[] ALIGN1 = "-HSa"
357 #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
390 #ifdef RLIMIT_NICE
391                         "e::"
392 #endif
393 #ifdef RLIMIT_RTPRIO
394                         "r::"
395 #endif
396                         ;
397
398 static 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)
408                 puts("unlimited");
409         else {
410                 val >>= l->factor_shift;
411                 printf("%llu\n", (long long) val);
412         }
413 }
414
415 int FAST_FUNC
416 shell_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          */
428         GETOPT_RESET();
429
430         argc = string_array_len(argv);
431
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) {
482                                                         bb_error_msg("invalid number '%s'", val_str);
483                                                         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);
488                                         /* 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;
493                                         if (opts & OPT_hard)
494                                                 limit.rlim_max = val;
495                                         if (opts & OPT_soft)
496                                                 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                 }
513         } /* while (there are options) */
514
515         return 0;
516 }