shell_common.c 13 KB

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