shell_common.c 12 KB

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