shell_common.c 11 KB

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