fixes for bugs found by make_single_applets.sh
[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         unsigned err;
61         unsigned end_ms; /* -t TIMEOUT */
62         int fd; /* -u FD */
63         int nchars; /* -n NUM */
64         char **pp;
65         char *buffer;
66         struct termios tty, old_tty;
67         const char *retval;
68         int bufpos; /* need to be able to hold -1 */
69         int startword;
70         smallint backslash;
71
72         errno = err = 0;
73
74         pp = argv;
75         while (*pp) {
76                 if (!is_well_formed_var_name(*pp, '\0')) {
77                         /* Mimic bash message */
78                         bb_error_msg("read: '%s': not a valid identifier", *pp);
79                         return (const char *)(uintptr_t)1;
80                 }
81                 pp++;
82         }
83
84         nchars = 0; /* if != 0, -n is in effect */
85         if (opt_n) {
86                 nchars = bb_strtou(opt_n, NULL, 10);
87                 if (nchars < 0 || errno)
88                         return "invalid count";
89                 /* note: "-n 0": off (bash 3.2 does this too) */
90         }
91         end_ms = 0;
92         if (opt_t) {
93                 end_ms = bb_strtou(opt_t, NULL, 10);
94                 if (errno || end_ms > UINT_MAX / 2048)
95                         return "invalid timeout";
96                 end_ms *= 1000;
97 #if 0 /* even bash has no -t N.NNN support */
98                 ts.tv_sec = bb_strtou(opt_t, &p, 10);
99                 ts.tv_usec = 0;
100                 /* EINVAL means number is ok, but not terminated by NUL */
101                 if (*p == '.' && errno == EINVAL) {
102                         char *p2;
103                         if (*++p) {
104                                 int scale;
105                                 ts.tv_usec = bb_strtou(p, &p2, 10);
106                                 if (errno)
107                                         return "invalid timeout";
108                                 scale = p2 - p;
109                                 /* normalize to usec */
110                                 if (scale > 6)
111                                         return "invalid timeout";
112                                 while (scale++ < 6)
113                                         ts.tv_usec *= 10;
114                         }
115                 } else if (ts.tv_sec < 0 || errno) {
116                         return "invalid timeout";
117                 }
118                 if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
119                         return "invalid timeout";
120                 }
121 #endif /* if 0 */
122         }
123         fd = STDIN_FILENO;
124         if (opt_u) {
125                 fd = bb_strtou(opt_u, NULL, 10);
126                 if (fd < 0 || errno)
127                         return "invalid file descriptor";
128         }
129
130         if (opt_p && isatty(fd)) {
131                 fputs(opt_p, stderr);
132                 fflush_all();
133         }
134
135         if (ifs == NULL)
136                 ifs = defifs;
137
138         if (nchars || (read_flags & BUILTIN_READ_SILENT)) {
139                 tcgetattr(fd, &tty);
140                 old_tty = tty;
141                 if (nchars) {
142                         tty.c_lflag &= ~ICANON;
143                         // Setting it to more than 1 breaks poll():
144                         // it blocks even if there's data. !??
145                         //tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
146                         /* reads will block only if < 1 char is available */
147                         tty.c_cc[VMIN] = 1;
148                         /* no timeout (reads block forever) */
149                         tty.c_cc[VTIME] = 0;
150                 }
151                 if (read_flags & BUILTIN_READ_SILENT) {
152                         tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
153                 }
154                 /* This forces execution of "restoring" tcgetattr later */
155                 read_flags |= BUILTIN_READ_SILENT;
156                 /* if tcgetattr failed, tcsetattr will fail too.
157                  * Ignoring, it's harmless. */
158                 tcsetattr(fd, TCSANOW, &tty);
159         }
160
161         retval = (const char *)(uintptr_t)0;
162         startword = 1;
163         backslash = 0;
164         if (end_ms) /* NB: end_ms stays nonzero: */
165                 end_ms = ((unsigned)monotonic_ms() + end_ms) | 1;
166         buffer = NULL;
167         bufpos = 0;
168         do {
169                 char c;
170                 struct pollfd pfd[1];
171                 int timeout;
172
173                 if ((bufpos & 0xff) == 0)
174                         buffer = xrealloc(buffer, bufpos + 0x101);
175
176                 timeout = -1;
177                 if (end_ms) {
178                         timeout = end_ms - (unsigned)monotonic_ms();
179                         if (timeout <= 0) { /* already late? */
180                                 retval = (const char *)(uintptr_t)1;
181                                 goto ret;
182                         }
183                 }
184
185                 /* We must poll even if timeout is -1:
186                  * we want to be interrupted if signal arrives,
187                  * regardless of SA_RESTART-ness of that signal!
188                  */
189                 errno = 0;
190                 pfd[0].fd = fd;
191                 pfd[0].events = POLLIN;
192                 if (poll(pfd, 1, timeout) != 1) {
193                         /* timed out, or EINTR */
194                         err = errno;
195                         retval = (const char *)(uintptr_t)1;
196                         goto ret;
197                 }
198                 if (read(fd, &buffer[bufpos], 1) != 1) {
199                         err = errno;
200                         retval = (const char *)(uintptr_t)1;
201                         break;
202                 }
203
204                 c = buffer[bufpos];
205                 if (c == '\0')
206                         continue;
207                 if (!(read_flags & BUILTIN_READ_RAW)) {
208                         if (backslash) {
209                                 backslash = 0;
210                                 if (c != '\n')
211                                         goto put;
212                                 continue;
213                         }
214                         if (c == '\\') {
215                                 backslash = 1;
216                                 continue;
217                         }
218                 }
219                 if (c == '\n')
220                         break;
221
222                 /* $IFS splitting. NOT done if we run "read"
223                  * without variable names (bash compat).
224                  * Thus, "read" and "read REPLY" are not the same.
225                  */
226                 if (argv[0]) {
227 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
228                         const char *is_ifs = strchr(ifs, c);
229                         if (startword && is_ifs) {
230                                 if (isspace(c))
231                                         continue;
232                                 /* it is a non-space ifs char */
233                                 startword--;
234                                 if (startword == 1) /* first one? */
235                                         continue; /* yes, it is not next word yet */
236                         }
237                         startword = 0;
238                         if (argv[1] != NULL && is_ifs) {
239                                 buffer[bufpos] = '\0';
240                                 bufpos = 0;
241                                 setvar(*argv, buffer);
242                                 argv++;
243                                 /* can we skip one non-space ifs char? (2: yes) */
244                                 startword = isspace(c) ? 2 : 1;
245                                 continue;
246                         }
247                 }
248  put:
249                 bufpos++;
250         } while (--nchars);
251
252         if (argv[0]) {
253                 /* Remove trailing space $IFS chars */
254                 while (--bufpos >= 0 && isspace(buffer[bufpos]) && strchr(ifs, buffer[bufpos]) != NULL)
255                         continue;
256                 buffer[bufpos + 1] = '\0';
257                 /* Use the remainder as a value for the next variable */
258                 setvar(*argv, buffer);
259                 /* Set the rest to "" */
260                 while (*++argv)
261                         setvar(*argv, "");
262         } else {
263                 /* Note: no $IFS removal */
264                 buffer[bufpos] = '\0';
265                 setvar("REPLY", buffer);
266         }
267
268  ret:
269         free(buffer);
270         if (read_flags & BUILTIN_READ_SILENT)
271                 tcsetattr(fd, TCSANOW, &old_tty);
272
273         errno = err;
274         return retval;
275 }
276
277 /* ulimit builtin */
278
279 struct limits {
280         uint8_t cmd;            /* RLIMIT_xxx fit into it */
281         uint8_t factor_shift;   /* shift by to get rlim_{cur,max} values */
282         char option;
283         const char *name;
284 };
285
286 static const struct limits limits_tbl[] = {
287 #ifdef RLIMIT_FSIZE
288         { RLIMIT_FSIZE,         9,      'f',    "file size (blocks)" },
289 #endif
290 #ifdef RLIMIT_CPU
291         { RLIMIT_CPU,           0,      't',    "cpu time (seconds)" },
292 #endif
293 #ifdef RLIMIT_DATA
294         { RLIMIT_DATA,          10,     'd',    "data seg size (kb)" },
295 #endif
296 #ifdef RLIMIT_STACK
297         { RLIMIT_STACK,         10,     's',    "stack size (kb)" },
298 #endif
299 #ifdef RLIMIT_CORE
300         { RLIMIT_CORE,          9,      'c',    "core file size (blocks)" },
301 #endif
302 #ifdef RLIMIT_RSS
303         { RLIMIT_RSS,           10,     'm',    "resident set size (kb)" },
304 #endif
305 #ifdef RLIMIT_MEMLOCK
306         { RLIMIT_MEMLOCK,       10,     'l',    "locked memory (kb)" },
307 #endif
308 #ifdef RLIMIT_NPROC
309         { RLIMIT_NPROC,         0,      'p',    "processes" },
310 #endif
311 #ifdef RLIMIT_NOFILE
312         { RLIMIT_NOFILE,        0,      'n',    "file descriptors" },
313 #endif
314 #ifdef RLIMIT_AS
315         { RLIMIT_AS,            10,     'v',    "address space (kb)" },
316 #endif
317 #ifdef RLIMIT_LOCKS
318         { RLIMIT_LOCKS,         0,      'w',    "locks" },
319 #endif
320 #ifdef RLIMIT_NICE
321         { RLIMIT_NICE,          0,      'e',    "scheduling priority" },
322 #endif
323 #ifdef RLIMIT_RTPRIO
324         { RLIMIT_RTPRIO,        0,      'r',    "real-time priority" },
325 #endif
326 };
327
328 enum {
329         OPT_hard = (1 << 0),
330         OPT_soft = (1 << 1),
331 };
332
333 /* "-": treat args as parameters of option with ASCII code 1 */
334 static const char ulimit_opt_string[] ALIGN1 = "-HSa"
335 #ifdef RLIMIT_FSIZE
336                         "f::"
337 #endif
338 #ifdef RLIMIT_CPU
339                         "t::"
340 #endif
341 #ifdef RLIMIT_DATA
342                         "d::"
343 #endif
344 #ifdef RLIMIT_STACK
345                         "s::"
346 #endif
347 #ifdef RLIMIT_CORE
348                         "c::"
349 #endif
350 #ifdef RLIMIT_RSS
351                         "m::"
352 #endif
353 #ifdef RLIMIT_MEMLOCK
354                         "l::"
355 #endif
356 #ifdef RLIMIT_NPROC
357                         "p::"
358 #endif
359 #ifdef RLIMIT_NOFILE
360                         "n::"
361 #endif
362 #ifdef RLIMIT_AS
363                         "v::"
364 #endif
365 #ifdef RLIMIT_LOCKS
366                         "w::"
367 #endif
368 #ifdef RLIMIT_NICE
369                         "e::"
370 #endif
371 #ifdef RLIMIT_RTPRIO
372                         "r::"
373 #endif
374                         ;
375
376 static void printlim(unsigned opts, const struct rlimit *limit,
377                         const struct limits *l)
378 {
379         rlim_t val;
380
381         val = limit->rlim_max;
382         if (!(opts & OPT_hard))
383                 val = limit->rlim_cur;
384
385         if (val == RLIM_INFINITY)
386                 puts("unlimited");
387         else {
388                 val >>= l->factor_shift;
389                 printf("%llu\n", (long long) val);
390         }
391 }
392
393 int FAST_FUNC
394 shell_builtin_ulimit(char **argv)
395 {
396         unsigned opts;
397         unsigned argc;
398
399         /* We can't use getopt32: need to handle commands like
400          * ulimit 123 -c2 -l 456
401          */
402
403         /* In case getopt was already called:
404          * reset the libc getopt() function, which keeps internal state.
405          */
406         GETOPT_RESET();
407
408         argc = string_array_len(argv);
409
410         opts = 0;
411         while (1) {
412                 struct rlimit limit;
413                 const struct limits *l;
414                 int opt_char = getopt(argc, argv, ulimit_opt_string);
415
416                 if (opt_char == -1)
417                         break;
418                 if (opt_char == 'H') {
419                         opts |= OPT_hard;
420                         continue;
421                 }
422                 if (opt_char == 'S') {
423                         opts |= OPT_soft;
424                         continue;
425                 }
426
427                 if (opt_char == 'a') {
428                         for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
429                                 getrlimit(l->cmd, &limit);
430                                 printf("-%c: %-30s ", l->option, l->name);
431                                 printlim(opts, &limit, l);
432                         }
433                         continue;
434                 }
435
436                 if (opt_char == 1)
437                         opt_char = 'f';
438                 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
439                         if (opt_char == l->option) {
440                                 char *val_str;
441
442                                 getrlimit(l->cmd, &limit);
443
444                                 val_str = optarg;
445                                 if (!val_str && argv[optind] && argv[optind][0] != '-')
446                                         val_str = argv[optind++]; /* ++ skips NN in "-c NN" case */
447                                 if (val_str) {
448                                         rlim_t val;
449
450                                         if (strcmp(val_str, "unlimited") == 0)
451                                                 val = RLIM_INFINITY;
452                                         else {
453                                                 if (sizeof(val) == sizeof(int))
454                                                         val = bb_strtou(val_str, NULL, 10);
455                                                 else if (sizeof(val) == sizeof(long))
456                                                         val = bb_strtoul(val_str, NULL, 10);
457                                                 else
458                                                         val = bb_strtoull(val_str, NULL, 10);
459                                                 if (errno) {
460                                                         bb_error_msg("invalid number '%s'", val_str);
461                                                         return EXIT_FAILURE;
462                                                 }
463                                                 val <<= l->factor_shift;
464                                         }
465 //bb_error_msg("opt %c val_str:'%s' val:%lld", opt_char, val_str, (long long)val);
466                                         /* from man bash: "If neither -H nor -S
467                                          * is specified, both the soft and hard
468                                          * limits are set. */
469                                         if (!opts)
470                                                 opts = OPT_hard + OPT_soft;
471                                         if (opts & OPT_hard)
472                                                 limit.rlim_max = val;
473                                         if (opts & OPT_soft)
474                                                 limit.rlim_cur = val;
475 //bb_error_msg("setrlimit(%d, %lld, %lld)", l->cmd, (long long)limit.rlim_cur, (long long)limit.rlim_max);
476                                         if (setrlimit(l->cmd, &limit) < 0) {
477                                                 bb_perror_msg("error setting limit");
478                                                 return EXIT_FAILURE;
479                                         }
480                                 } else {
481                                         printlim(opts, &limit, l);
482                                 }
483                                 break;
484                         }
485                 } /* for (every possible opt) */
486
487                 if (l == &limits_tbl[ARRAY_SIZE(limits_tbl)]) {
488                         /* bad option. getopt already complained. */
489                         break;
490                 }
491         } /* while (there are options) */
492
493         return 0;
494 }