3
0

shell_common.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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(struct builtin_read_params *params)
  43. {
  44. struct pollfd pfd[1];
  45. #define fd (pfd[0].fd) /* -u FD */
  46. unsigned err;
  47. unsigned end_ms; /* -t TIMEOUT */
  48. int nchars; /* -n NUM */
  49. char **pp;
  50. char *buffer;
  51. char delim;
  52. struct termios tty, old_tty;
  53. const char *retval;
  54. int bufpos; /* need to be able to hold -1 */
  55. int startword;
  56. smallint backslash;
  57. char **argv;
  58. const char *ifs;
  59. int read_flags;
  60. errno = err = 0;
  61. argv = params->argv;
  62. pp = argv;
  63. while (*pp) {
  64. if (!is_well_formed_var_name(*pp, '\0')) {
  65. /* Mimic bash message */
  66. bb_error_msg("read: '%s': not a valid identifier", *pp);
  67. return (const char *)(uintptr_t)1;
  68. }
  69. pp++;
  70. }
  71. nchars = 0; /* if != 0, -n is in effect */
  72. if (params->opt_n) {
  73. nchars = bb_strtou(params->opt_n, NULL, 10);
  74. if (nchars < 0 || errno)
  75. return "invalid count";
  76. /* note: "-n 0": off (bash 3.2 does this too) */
  77. }
  78. end_ms = 0;
  79. if (params->opt_t && !ENABLE_FEATURE_SH_READ_FRAC) {
  80. end_ms = bb_strtou(params->opt_t, NULL, 10);
  81. if (errno)
  82. return "invalid timeout";
  83. if (end_ms > UINT_MAX / 2048) /* be safely away from overflow */
  84. end_ms = UINT_MAX / 2048;
  85. end_ms *= 1000;
  86. }
  87. if (params->opt_t && ENABLE_FEATURE_SH_READ_FRAC) {
  88. /* bash 4.3 (maybe earlier) supports -t N.NNNNNN */
  89. char *p;
  90. /* Eat up to three fractional digits */
  91. int frac_digits = 3 + 1;
  92. end_ms = bb_strtou(params->opt_t, &p, 10);
  93. if (end_ms > UINT_MAX / 2048) /* be safely away from overflow */
  94. end_ms = UINT_MAX / 2048;
  95. if (errno) {
  96. /* EINVAL = number is ok, but not NUL terminated */
  97. if (errno != EINVAL || *p != '.')
  98. return "invalid timeout";
  99. /* Do not check the rest: bash allows "0.123456xyz" */
  100. while (*++p && --frac_digits) {
  101. end_ms *= 10;
  102. end_ms += (*p - '0');
  103. if ((unsigned char)(*p - '0') > 9)
  104. return "invalid timeout";
  105. }
  106. }
  107. while (--frac_digits > 0) {
  108. end_ms *= 10;
  109. }
  110. }
  111. fd = STDIN_FILENO;
  112. if (params->opt_u) {
  113. fd = bb_strtou(params->opt_u, NULL, 10);
  114. if (fd < 0 || errno)
  115. return "invalid file descriptor";
  116. }
  117. if (params->opt_t && end_ms == 0) {
  118. /* "If timeout is 0, read returns immediately, without trying
  119. * to read any data. The exit status is 0 if input is available
  120. * on the specified file descriptor, non-zero otherwise."
  121. * bash seems to ignore -p PROMPT for this use case.
  122. */
  123. int r;
  124. pfd[0].events = POLLIN;
  125. r = poll(pfd, 1, /*timeout:*/ 0);
  126. /* Return 0 only if poll returns 1 ("one fd ready"), else return 1: */
  127. return (const char *)(uintptr_t)(r <= 0);
  128. }
  129. if (params->opt_p && isatty(fd)) {
  130. fputs(params->opt_p, stderr);
  131. fflush_all();
  132. }
  133. ifs = params->ifs;
  134. if (ifs == NULL)
  135. ifs = defifs;
  136. read_flags = params->read_flags;
  137. if (nchars || (read_flags & BUILTIN_READ_SILENT)) {
  138. tcgetattr(fd, &tty);
  139. old_tty = tty;
  140. if (nchars) {
  141. tty.c_lflag &= ~ICANON;
  142. // Setting it to more than 1 breaks poll():
  143. // it blocks even if there's data. !??
  144. //tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
  145. /* reads will block only if < 1 char is available */
  146. tty.c_cc[VMIN] = 1;
  147. /* no timeout (reads block forever) */
  148. tty.c_cc[VTIME] = 0;
  149. }
  150. if (read_flags & BUILTIN_READ_SILENT) {
  151. tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
  152. }
  153. /* This forces execution of "restoring" tcgetattr later */
  154. read_flags |= BUILTIN_READ_SILENT;
  155. /* if tcgetattr failed, tcsetattr will fail too.
  156. * Ignoring, it's harmless. */
  157. tcsetattr(fd, TCSANOW, &tty);
  158. }
  159. retval = (const char *)(uintptr_t)0;
  160. startword = 1;
  161. backslash = 0;
  162. if (params->opt_t)
  163. end_ms += (unsigned)monotonic_ms();
  164. buffer = NULL;
  165. bufpos = 0;
  166. delim = params->opt_d ? params->opt_d[0] : '\n';
  167. do {
  168. char c;
  169. int timeout;
  170. if ((bufpos & 0xff) == 0)
  171. buffer = xrealloc(buffer, bufpos + 0x101);
  172. timeout = -1;
  173. if (params->opt_t) {
  174. timeout = end_ms - (unsigned)monotonic_ms();
  175. /* ^^^^^^^^^^^^^ all values are unsigned,
  176. * wrapping math is used here, good even if
  177. * 32-bit unix time wrapped (year 2038+).
  178. */
  179. if (timeout <= 0) { /* already late? */
  180. retval = (const char *)(uintptr_t)1;
  181. goto ret;
  182. }
  183. }
  184. /* We must poll even if timeout is -1:
  185. * we want to be interrupted if signal arrives,
  186. * regardless of SA_RESTART-ness of that signal!
  187. */
  188. errno = 0;
  189. pfd[0].events = POLLIN;
  190. if (poll(pfd, 1, timeout) <= 0) {
  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. c = buffer[bufpos];
  202. if (c == '\0')
  203. continue;
  204. if (!(read_flags & BUILTIN_READ_RAW)) {
  205. if (backslash) {
  206. backslash = 0;
  207. if (c != '\n')
  208. goto put;
  209. continue;
  210. }
  211. if (c == '\\') {
  212. backslash = 1;
  213. continue;
  214. }
  215. }
  216. if (c == delim) /* '\n' or -d CHAR */
  217. break;
  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 (!params->opt_d && 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. params->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. if (argv[0]) {
  248. /* Remove trailing space $IFS chars */
  249. while (--bufpos >= 0
  250. && isspace(buffer[bufpos])
  251. && strchr(ifs, buffer[bufpos]) != NULL
  252. ) {
  253. continue;
  254. }
  255. buffer[bufpos + 1] = '\0';
  256. /* Last variable takes the entire remainder with delimiters
  257. * (sans trailing whitespace $IFS),
  258. * but ***only "if there are fewer vars than fields"(c)***!
  259. * The "X:Y:" case below: there are two fields,
  260. * and therefore last delimiter (:) is eaten:
  261. * IFS=": "
  262. * echo "X:Y:Z:" | (read x y; echo "|$x|$y|") # |X|Y:Z:|
  263. * echo "X:Y:Z" | (read x y; echo "|$x|$y|") # |X|Y:Z|
  264. * echo "X:Y:" | (read x y; echo "|$x|$y|") # |X|Y|, not |X|Y:|
  265. * echo "X:Y : " | (read x y; echo "|$x|$y|") # |X|Y|
  266. */
  267. if (bufpos >= 0
  268. && strchr(ifs, buffer[bufpos]) != NULL
  269. ) {
  270. /* There _is_ a non-whitespace IFS char */
  271. /* Skip whitespace IFS char before it */
  272. while (--bufpos >= 0
  273. && isspace(buffer[bufpos])
  274. && strchr(ifs, buffer[bufpos]) != NULL
  275. ) {
  276. continue;
  277. }
  278. /* Are there $IFS chars? */
  279. if (strcspn(buffer, ifs) >= ++bufpos) {
  280. /* No: last var takes one field, not more */
  281. /* So, drop trailing IFS delims */
  282. buffer[bufpos] = '\0';
  283. }
  284. }
  285. /* Use the remainder as a value for the next variable */
  286. params->setvar(*argv, buffer);
  287. /* Set the rest to "" */
  288. while (*++argv)
  289. params->setvar(*argv, "");
  290. } else {
  291. /* Note: no $IFS removal */
  292. buffer[bufpos] = '\0';
  293. params->setvar("REPLY", buffer);
  294. }
  295. ret:
  296. free(buffer);
  297. if (read_flags & BUILTIN_READ_SILENT)
  298. tcsetattr(fd, TCSANOW, &old_tty);
  299. errno = err;
  300. return retval;
  301. #undef fd
  302. }
  303. /* ulimit builtin */
  304. struct limits {
  305. uint8_t cmd; /* RLIMIT_xxx fit into it */
  306. uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
  307. char option;
  308. const char *name;
  309. };
  310. static const struct limits limits_tbl[] = {
  311. #ifdef RLIMIT_FSIZE
  312. { RLIMIT_FSIZE, 9, 'f', "file size (blocks)" },
  313. #endif
  314. #ifdef RLIMIT_CPU
  315. { RLIMIT_CPU, 0, 't', "cpu time (seconds)" },
  316. #endif
  317. #ifdef RLIMIT_DATA
  318. { RLIMIT_DATA, 10, 'd', "data seg size (kb)" },
  319. #endif
  320. #ifdef RLIMIT_STACK
  321. { RLIMIT_STACK, 10, 's', "stack size (kb)" },
  322. #endif
  323. #ifdef RLIMIT_CORE
  324. { RLIMIT_CORE, 9, 'c', "core file size (blocks)" },
  325. #endif
  326. #ifdef RLIMIT_RSS
  327. { RLIMIT_RSS, 10, 'm', "resident set size (kb)" },
  328. #endif
  329. #ifdef RLIMIT_MEMLOCK
  330. { RLIMIT_MEMLOCK, 10, 'l', "locked memory (kb)" },
  331. #endif
  332. #ifdef RLIMIT_NPROC
  333. { RLIMIT_NPROC, 0, 'p', "processes" },
  334. #endif
  335. #ifdef RLIMIT_NOFILE
  336. { RLIMIT_NOFILE, 0, 'n', "file descriptors" },
  337. #endif
  338. #ifdef RLIMIT_AS
  339. { RLIMIT_AS, 10, 'v', "address space (kb)" },
  340. #endif
  341. #ifdef RLIMIT_LOCKS
  342. { RLIMIT_LOCKS, 0, 'w', "locks" },
  343. #endif
  344. #ifdef RLIMIT_NICE
  345. { RLIMIT_NICE, 0, 'e', "scheduling priority" },
  346. #endif
  347. #ifdef RLIMIT_RTPRIO
  348. { RLIMIT_RTPRIO, 0, 'r', "real-time priority" },
  349. #endif
  350. };
  351. enum {
  352. OPT_hard = (1 << 0),
  353. OPT_soft = (1 << 1),
  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. static void printlim(unsigned opts, const struct rlimit *limit,
  398. const struct limits *l)
  399. {
  400. rlim_t val;
  401. val = limit->rlim_max;
  402. if (!(opts & OPT_hard))
  403. val = limit->rlim_cur;
  404. if (val == RLIM_INFINITY)
  405. puts("unlimited");
  406. else {
  407. val >>= l->factor_shift;
  408. printf("%llu\n", (long long) val);
  409. }
  410. }
  411. int FAST_FUNC
  412. shell_builtin_ulimit(char **argv)
  413. {
  414. unsigned opts;
  415. unsigned argc;
  416. /* We can't use getopt32: need to handle commands like
  417. * ulimit 123 -c2 -l 456
  418. */
  419. /* In case getopt() was already called:
  420. * reset libc getopt() internal state.
  421. */
  422. GETOPT_RESET();
  423. argc = string_array_len(argv);
  424. opts = 0;
  425. while (1) {
  426. struct rlimit limit;
  427. const struct limits *l;
  428. int opt_char = getopt(argc, argv, ulimit_opt_string);
  429. if (opt_char == -1)
  430. break;
  431. if (opt_char == 'H') {
  432. opts |= OPT_hard;
  433. continue;
  434. }
  435. if (opt_char == 'S') {
  436. opts |= OPT_soft;
  437. continue;
  438. }
  439. if (opt_char == 'a') {
  440. for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
  441. getrlimit(l->cmd, &limit);
  442. printf("-%c: %-30s ", l->option, l->name);
  443. printlim(opts, &limit, l);
  444. }
  445. continue;
  446. }
  447. if (opt_char == 1)
  448. opt_char = 'f';
  449. for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
  450. if (opt_char == l->option) {
  451. char *val_str;
  452. getrlimit(l->cmd, &limit);
  453. val_str = optarg;
  454. if (!val_str && argv[optind] && argv[optind][0] != '-')
  455. val_str = argv[optind++]; /* ++ skips NN in "-c NN" case */
  456. if (val_str) {
  457. rlim_t val;
  458. if (strcmp(val_str, "unlimited") == 0)
  459. val = RLIM_INFINITY;
  460. else {
  461. if (sizeof(val) == sizeof(int))
  462. val = bb_strtou(val_str, NULL, 10);
  463. else if (sizeof(val) == sizeof(long))
  464. val = bb_strtoul(val_str, NULL, 10);
  465. else
  466. val = bb_strtoull(val_str, NULL, 10);
  467. if (errno) {
  468. bb_error_msg("invalid number '%s'", val_str);
  469. return EXIT_FAILURE;
  470. }
  471. val <<= l->factor_shift;
  472. }
  473. //bb_error_msg("opt %c val_str:'%s' val:%lld", opt_char, val_str, (long long)val);
  474. /* from man bash: "If neither -H nor -S
  475. * is specified, both the soft and hard
  476. * limits are set. */
  477. if (!opts)
  478. opts = OPT_hard + OPT_soft;
  479. if (opts & OPT_hard)
  480. limit.rlim_max = val;
  481. if (opts & OPT_soft)
  482. limit.rlim_cur = val;
  483. //bb_error_msg("setrlimit(%d, %lld, %lld)", l->cmd, (long long)limit.rlim_cur, (long long)limit.rlim_max);
  484. if (setrlimit(l->cmd, &limit) < 0) {
  485. bb_perror_msg("error setting limit");
  486. return EXIT_FAILURE;
  487. }
  488. } else {
  489. printlim(opts, &limit, l);
  490. }
  491. break;
  492. }
  493. } /* for (every possible opt) */
  494. if (l == &limits_tbl[ARRAY_SIZE(limits_tbl)]) {
  495. /* bad option. getopt already complained. */
  496. break;
  497. }
  498. } /* while (there are options) */
  499. return 0;
  500. }