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