appletlib.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) tons of folks. Tracking down who wrote what
  6. * isn't something I'm going to worry about... If you wrote something
  7. * here, please feel free to acknowledge your work.
  8. *
  9. * Based in part on code from sash, Copyright (c) 1999 by David I. Bell
  10. * Permission has been granted to redistribute this code under GPL.
  11. *
  12. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  13. */
  14. /* We are trying to not use printf, this benefits the case when selected
  15. * applets are really simple. Example:
  16. *
  17. * $ ./busybox
  18. * ...
  19. * Currently defined functions:
  20. * basename, false, true
  21. *
  22. * $ size busybox
  23. * text data bss dec hex filename
  24. * 4473 52 72 4597 11f5 busybox
  25. *
  26. * FEATURE_INSTALLER or FEATURE_SUID will still link printf routines in. :(
  27. */
  28. #include "busybox.h"
  29. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  30. || defined(__APPLE__) \
  31. )
  32. # include <malloc.h> /* for mallopt */
  33. #endif
  34. /* Declare <applet>_main() */
  35. #define PROTOTYPES
  36. #include "applets.h"
  37. #undef PROTOTYPES
  38. /* Include generated applet names, pointers to <applet>_main, etc */
  39. #include "applet_tables.h"
  40. /* ...and if applet_tables generator says we have only one applet... */
  41. #ifdef SINGLE_APPLET_MAIN
  42. # undef ENABLE_FEATURE_INDIVIDUAL
  43. # define ENABLE_FEATURE_INDIVIDUAL 1
  44. # undef IF_FEATURE_INDIVIDUAL
  45. # define IF_FEATURE_INDIVIDUAL(...) __VA_ARGS__
  46. #endif
  47. #include "usage_compressed.h"
  48. /* "Do not compress usage text if uncompressed text is small
  49. * and we don't include bunzip2 code for other reasons"
  50. *
  51. * Useful for mass one-applet rebuild (bunzip2 code is ~2.7k).
  52. *
  53. * Unlike BUNZIP2, if FEATURE_SEAMLESS_BZ2 is on, bunzip2 code is built but
  54. * still may be unused if none of the selected applets calls open_zipped()
  55. * or its friends; we test for (FEATURE_SEAMLESS_BZ2 && <APPLET>) instead.
  56. * For example, only if TAR and FEATURE_SEAMLESS_BZ2 are both selected,
  57. * then bunzip2 code will be linked in anyway, and disabling help compression
  58. * would be not optimal:
  59. */
  60. #if UNPACKED_USAGE_LENGTH < 4*1024 \
  61. && !(ENABLE_FEATURE_SEAMLESS_BZ2 && ENABLE_TAR) \
  62. && !(ENABLE_FEATURE_SEAMLESS_BZ2 && ENABLE_MODPROBE) \
  63. && !(ENABLE_FEATURE_SEAMLESS_BZ2 && ENABLE_INSMOD) \
  64. && !(ENABLE_FEATURE_SEAMLESS_BZ2 && ENABLE_DEPMOD) \
  65. && !(ENABLE_FEATURE_SEAMLESS_BZ2 && ENABLE_MAN) \
  66. && !ENABLE_BUNZIP2 \
  67. && !ENABLE_BZCAT
  68. # undef ENABLE_FEATURE_COMPRESS_USAGE
  69. # define ENABLE_FEATURE_COMPRESS_USAGE 0
  70. #endif
  71. unsigned FAST_FUNC string_array_len(char **argv)
  72. {
  73. char **start = argv;
  74. while (*argv)
  75. argv++;
  76. return argv - start;
  77. }
  78. #if ENABLE_SHOW_USAGE && !ENABLE_FEATURE_COMPRESS_USAGE
  79. static const char usage_messages[] ALIGN1 = UNPACKED_USAGE;
  80. #else
  81. # define usage_messages 0
  82. #endif
  83. #if ENABLE_FEATURE_COMPRESS_USAGE
  84. static const char packed_usage[] ALIGN1 = { PACKED_USAGE };
  85. # include "bb_archive.h"
  86. static const char *unpack_usage_messages(void)
  87. {
  88. char *outbuf = NULL;
  89. bunzip_data *bd;
  90. int i;
  91. i = start_bunzip(&bd,
  92. /* src_fd: */ -1,
  93. /* inbuf: */ packed_usage,
  94. /* len: */ sizeof(packed_usage));
  95. /* read_bunzip can longjmp to start_bunzip, and ultimately
  96. * end up here with i != 0 on read data errors! Not trivial */
  97. if (!i) {
  98. /* Cannot use xmalloc: will leak bd in NOFORK case! */
  99. outbuf = malloc_or_warn(sizeof(UNPACKED_USAGE));
  100. if (outbuf)
  101. read_bunzip(bd, outbuf, sizeof(UNPACKED_USAGE));
  102. }
  103. dealloc_bunzip(bd);
  104. return outbuf;
  105. }
  106. # define dealloc_usage_messages(s) free(s)
  107. #else
  108. # define unpack_usage_messages() usage_messages
  109. # define dealloc_usage_messages(s) ((void)(s))
  110. #endif /* FEATURE_COMPRESS_USAGE */
  111. void FAST_FUNC bb_show_usage(void)
  112. {
  113. if (ENABLE_SHOW_USAGE) {
  114. #ifdef SINGLE_APPLET_STR
  115. /* Imagine that this applet is "true". Dont suck in printf! */
  116. const char *usage_string = unpack_usage_messages();
  117. if (*usage_string == '\b') {
  118. full_write2_str("No help available.\n\n");
  119. } else {
  120. full_write2_str("Usage: "SINGLE_APPLET_STR" ");
  121. full_write2_str(usage_string);
  122. full_write2_str("\n\n");
  123. }
  124. if (ENABLE_FEATURE_CLEAN_UP)
  125. dealloc_usage_messages((char*)usage_string);
  126. #else
  127. const char *p;
  128. const char *usage_string = p = unpack_usage_messages();
  129. int ap = find_applet_by_name(applet_name);
  130. if (ap < 0) /* never happens, paranoia */
  131. xfunc_die();
  132. while (ap) {
  133. while (*p++) continue;
  134. ap--;
  135. }
  136. full_write2_str(bb_banner);
  137. full_write2_str(" multi-call binary.\n");
  138. if (*p == '\b')
  139. full_write2_str("\nNo help available.\n\n");
  140. else {
  141. full_write2_str("\nUsage: ");
  142. full_write2_str(applet_name);
  143. full_write2_str(" ");
  144. full_write2_str(p);
  145. full_write2_str("\n");
  146. }
  147. if (ENABLE_FEATURE_CLEAN_UP)
  148. dealloc_usage_messages((char*)usage_string);
  149. #endif
  150. }
  151. xfunc_die();
  152. }
  153. int FAST_FUNC find_applet_by_name(const char *name)
  154. {
  155. unsigned i, max;
  156. int j;
  157. const char *p;
  158. /* The commented-out word-at-a-time code is ~40% faster, but +160 bytes.
  159. * "Faster" here saves ~0.5 microsecond of real time - not worth it.
  160. */
  161. #if 0 /*BB_UNALIGNED_MEMACCESS_OK && BB_LITTLE_ENDIAN*/
  162. uint32_t n32;
  163. /* Handle all names < 2 chars long early */
  164. if (name[0] == '\0')
  165. return -1; /* "" is not a valid applet name */
  166. if (name[1] == '\0') {
  167. if (!ENABLE_TEST)
  168. return -1; /* 1-char name is not valid */
  169. if (name[0] != ']')
  170. return -1; /* 1-char name which isn't "[" is not valid */
  171. /* applet "[" is always applet #0: */
  172. return 0;
  173. }
  174. #endif
  175. p = applet_names;
  176. i = 0;
  177. #if KNOWN_APPNAME_OFFSETS <= 0
  178. max = NUM_APPLETS;
  179. #else
  180. max = NUM_APPLETS * KNOWN_APPNAME_OFFSETS;
  181. for (j = ARRAY_SIZE(applet_nameofs)-1; j >= 0; j--) {
  182. const char *pp = applet_names + applet_nameofs[j];
  183. if (strcmp(name, pp) >= 0) {
  184. //bb_error_msg("name:'%s' >= pp:'%s'", name, pp);
  185. p = pp;
  186. i = max - NUM_APPLETS;
  187. break;
  188. }
  189. max -= NUM_APPLETS;
  190. }
  191. max /= (unsigned)KNOWN_APPNAME_OFFSETS;
  192. i /= (unsigned)KNOWN_APPNAME_OFFSETS;
  193. //bb_error_msg("name:'%s' starting from:'%s' i:%u max:%u", name, p, i, max);
  194. #endif
  195. /* Open-coded linear search without strcmp/strlen calls for speed */
  196. #if 0 /*BB_UNALIGNED_MEMACCESS_OK && BB_LITTLE_ENDIAN*/
  197. /* skip "[\0" name, it's surely not it */
  198. if (ENABLE_TEST && LONE_CHAR(p, '['))
  199. i++, p += 2;
  200. /* All remaining applet names in p[] are at least 2 chars long */
  201. /* name[] is also at least 2 chars long */
  202. n32 = (name[0] << 0) | (name[1] << 8) | (name[2] << 16);
  203. while (i < max) {
  204. uint32_t p32;
  205. char ch;
  206. /* Quickly check match of the first 3 bytes */
  207. move_from_unaligned32(p32, p);
  208. p += 3;
  209. if ((p32 & 0x00ffffff) != n32) {
  210. /* Most likely case: 3 first bytes do not match */
  211. i++;
  212. if ((p32 & 0x00ff0000) == '\0')
  213. continue; // p[2] was NUL
  214. p++;
  215. if ((p32 & 0xff000000) == '\0')
  216. continue; // p[3] was NUL
  217. /* p[0..3] aren't matching and none is NUL, check the rest */
  218. while (*p++ != '\0')
  219. continue;
  220. continue;
  221. }
  222. /* Unlikely branch: first 3 bytes ([0..2]) match */
  223. if ((p32 & 0x00ff0000) == '\0') {
  224. /* name is 2-byte long, it is full match */
  225. //bb_error_msg("found:'%s' i:%u", name, i);
  226. return i;
  227. }
  228. /* Check remaining bytes [3..NUL] */
  229. ch = (p32 >> 24);
  230. j = 3;
  231. while (ch == name[j]) {
  232. if (ch == '\0') {
  233. //bb_error_msg("found:'%s' i:%u", name, i);
  234. return i;
  235. }
  236. ch = *++p;
  237. j++;
  238. }
  239. /* Not a match. Skip it, including NUL */
  240. while (ch != '\0')
  241. ch = *++p;
  242. p++;
  243. i++;
  244. }
  245. return -1;
  246. #else
  247. while (i < max) {
  248. char ch;
  249. j = 0;
  250. /* Do we see "name\0" in applet_names[p] position? */
  251. while ((ch = *p) == name[j]) {
  252. if (ch == '\0') {
  253. //bb_error_msg("found:'%s' i:%u", name, i);
  254. return i; /* yes */
  255. }
  256. p++;
  257. j++;
  258. }
  259. /* No.
  260. * p => 1st non-matching char in applet_names[],
  261. * skip to and including NUL.
  262. */
  263. while (ch != '\0')
  264. ch = *++p;
  265. p++;
  266. i++;
  267. }
  268. return -1;
  269. #endif
  270. }
  271. void lbb_prepare(const char *applet
  272. IF_FEATURE_INDIVIDUAL(, char **argv))
  273. MAIN_EXTERNALLY_VISIBLE;
  274. void lbb_prepare(const char *applet
  275. IF_FEATURE_INDIVIDUAL(, char **argv))
  276. {
  277. #ifdef __GLIBC__
  278. (*(int **)&bb_errno) = __errno_location();
  279. barrier();
  280. #endif
  281. applet_name = applet;
  282. if (ENABLE_LOCALE_SUPPORT)
  283. setlocale(LC_ALL, "");
  284. #if ENABLE_FEATURE_INDIVIDUAL
  285. /* Redundant for busybox (run_applet_and_exit covers that case)
  286. * but needed for "individual applet" mode */
  287. if (argv[1]
  288. && !argv[2]
  289. && strcmp(argv[1], "--help") == 0
  290. && !is_prefixed_with(applet, "busybox")
  291. ) {
  292. /* Special case. POSIX says "test --help"
  293. * should be no different from e.g. "test --foo". */
  294. if (!ENABLE_TEST || strcmp(applet_name, "test") != 0)
  295. bb_show_usage();
  296. }
  297. #endif
  298. }
  299. /* The code below can well be in applets/applets.c, as it is used only
  300. * for busybox binary, not "individual" binaries.
  301. * However, keeping it here and linking it into libbusybox.so
  302. * (together with remaining tiny applets/applets.o)
  303. * makes it possible to avoid --whole-archive at link time.
  304. * This makes (shared busybox) + libbusybox smaller.
  305. * (--gc-sections would be even better....)
  306. */
  307. const char *applet_name;
  308. #if !BB_MMU
  309. bool re_execed;
  310. #endif
  311. /* If not built as a single-applet executable... */
  312. #if !defined(SINGLE_APPLET_MAIN)
  313. IF_FEATURE_SUID(static uid_t ruid;) /* real uid */
  314. # if ENABLE_FEATURE_SUID_CONFIG
  315. static struct suid_config_t {
  316. /* next ptr must be first: this struct needs to be llist-compatible */
  317. struct suid_config_t *m_next;
  318. struct bb_uidgid_t m_ugid;
  319. int m_applet;
  320. mode_t m_mode;
  321. } *suid_config;
  322. static bool suid_cfg_readable;
  323. /* libbb candidate */
  324. static char *get_trimmed_slice(char *s, char *e)
  325. {
  326. /* First, consider the value at e to be nul and back up until we
  327. * reach a non-space char. Set the char after that (possibly at
  328. * the original e) to nul. */
  329. while (e-- > s) {
  330. if (!isspace(*e)) {
  331. break;
  332. }
  333. }
  334. e[1] = '\0';
  335. /* Next, advance past all leading space and return a ptr to the
  336. * first non-space char; possibly the terminating nul. */
  337. return skip_whitespace(s);
  338. }
  339. static void parse_config_file(void)
  340. {
  341. /* Don't depend on the tools to combine strings. */
  342. static const char config_file[] ALIGN1 = "/etc/busybox.conf";
  343. struct suid_config_t *sct_head;
  344. int applet_no;
  345. FILE *f;
  346. const char *errmsg;
  347. unsigned lc;
  348. smallint section;
  349. struct stat st;
  350. ruid = getuid();
  351. if (ruid == 0) /* run by root - don't need to even read config file */
  352. return;
  353. if ((stat(config_file, &st) != 0) /* No config file? */
  354. || !S_ISREG(st.st_mode) /* Not a regular file? */
  355. || (st.st_uid != 0) /* Not owned by root? */
  356. || (st.st_mode & (S_IWGRP | S_IWOTH)) /* Writable by non-root? */
  357. || !(f = fopen_for_read(config_file)) /* Cannot open? */
  358. ) {
  359. return;
  360. }
  361. suid_cfg_readable = 1;
  362. sct_head = NULL;
  363. section = lc = 0;
  364. while (1) {
  365. char buffer[256];
  366. char *s;
  367. if (!fgets(buffer, sizeof(buffer), f)) { /* Are we done? */
  368. // Looks like bloat
  369. //if (ferror(f)) { /* Make sure it wasn't a read error. */
  370. // errmsg = "reading";
  371. // goto pe_label;
  372. //}
  373. fclose(f);
  374. suid_config = sct_head; /* Success, so set the pointer. */
  375. return;
  376. }
  377. s = buffer;
  378. lc++; /* Got a (partial) line. */
  379. /* If a line is too long for our buffer, we consider it an error.
  380. * The following test does mistreat one corner case though.
  381. * If the final line of the file does not end with a newline and
  382. * yet exactly fills the buffer, it will be treated as too long
  383. * even though there isn't really a problem. But it isn't really
  384. * worth adding code to deal with such an unlikely situation, and
  385. * we do err on the side of caution. Besides, the line would be
  386. * too long if it did end with a newline. */
  387. if (!strchr(s, '\n') && !feof(f)) {
  388. errmsg = "line too long";
  389. goto pe_label;
  390. }
  391. /* Trim leading and trailing whitespace, ignoring comments, and
  392. * check if the resulting string is empty. */
  393. s = get_trimmed_slice(s, strchrnul(s, '#'));
  394. if (!*s) {
  395. continue;
  396. }
  397. /* Check for a section header. */
  398. if (*s == '[') {
  399. /* Unlike the old code, we ignore leading and trailing
  400. * whitespace for the section name. We also require that
  401. * there are no stray characters after the closing bracket. */
  402. char *e = strchr(s, ']');
  403. if (!e /* Missing right bracket? */
  404. || e[1] /* Trailing characters? */
  405. || !*(s = get_trimmed_slice(s+1, e)) /* Missing name? */
  406. ) {
  407. errmsg = "section header";
  408. goto pe_label;
  409. }
  410. /* Right now we only have one section so just check it.
  411. * If more sections are added in the future, please don't
  412. * resort to cascading ifs with multiple strcasecmp calls.
  413. * That kind of bloated code is all too common. A loop
  414. * and a string table would be a better choice unless the
  415. * number of sections is very small. */
  416. if (strcasecmp(s, "SUID") == 0) {
  417. section = 1;
  418. continue;
  419. }
  420. section = -1; /* Unknown section so set to skip. */
  421. continue;
  422. }
  423. /* Process sections. */
  424. if (section == 1) { /* SUID */
  425. /* Since we trimmed leading and trailing space above, we're
  426. * now looking for strings of the form
  427. * <key>[::space::]*=[::space::]*<value>
  428. * where both key and value could contain inner whitespace. */
  429. /* First get the key (an applet name in our case). */
  430. char *e = strchr(s, '=');
  431. if (e) {
  432. s = get_trimmed_slice(s, e);
  433. }
  434. if (!e || !*s) { /* Missing '=' or empty key. */
  435. errmsg = "keyword";
  436. goto pe_label;
  437. }
  438. /* Ok, we have an applet name. Process the rhs if this
  439. * applet is currently built in and ignore it otherwise.
  440. * Note: this can hide config file bugs which only pop
  441. * up when the busybox configuration is changed. */
  442. applet_no = find_applet_by_name(s);
  443. if (applet_no >= 0) {
  444. unsigned i;
  445. struct suid_config_t *sct;
  446. /* Note: We currently don't check for duplicates!
  447. * The last config line for each applet will be the
  448. * one used since we insert at the head of the list.
  449. * I suppose this could be considered a feature. */
  450. sct = xzalloc(sizeof(*sct));
  451. sct->m_applet = applet_no;
  452. /*sct->m_mode = 0;*/
  453. sct->m_next = sct_head;
  454. sct_head = sct;
  455. /* Get the specified mode. */
  456. e = skip_whitespace(e+1);
  457. for (i = 0; i < 3; i++) {
  458. /* There are 4 chars for each of user/group/other.
  459. * "x-xx" instead of "x-" are to make
  460. * "idx > 3" check catch invalid chars.
  461. */
  462. static const char mode_chars[] ALIGN1 = "Ssx-" "Ssx-" "x-xx";
  463. static const unsigned short mode_mask[] ALIGN2 = {
  464. S_ISUID, S_ISUID|S_IXUSR, S_IXUSR, 0, /* Ssx- */
  465. S_ISGID, S_ISGID|S_IXGRP, S_IXGRP, 0, /* Ssx- */
  466. S_IXOTH, 0 /* x- */
  467. };
  468. const char *q = strchrnul(mode_chars + 4*i, *e);
  469. unsigned idx = q - (mode_chars + 4*i);
  470. if (idx > 3) {
  471. errmsg = "mode";
  472. goto pe_label;
  473. }
  474. sct->m_mode |= mode_mask[q - mode_chars];
  475. e++;
  476. }
  477. /* Now get the user/group info. */
  478. s = skip_whitespace(e);
  479. /* Default is 0.0, else parse USER.GROUP: */
  480. if (*s) {
  481. /* We require whitespace between mode and USER.GROUP */
  482. if ((s == e) || !(e = strchr(s, '.'))) {
  483. errmsg = "uid.gid";
  484. goto pe_label;
  485. }
  486. *e = ':'; /* get_uidgid needs USER:GROUP syntax */
  487. if (get_uidgid(&sct->m_ugid, s) == 0) {
  488. errmsg = "unknown user/group";
  489. goto pe_label;
  490. }
  491. }
  492. }
  493. continue;
  494. }
  495. /* Unknown sections are ignored. */
  496. /* Encountering configuration lines prior to seeing a
  497. * section header is treated as an error. This is how
  498. * the old code worked, but it may not be desirable.
  499. * We may want to simply ignore such lines in case they
  500. * are used in some future version of busybox. */
  501. if (!section) {
  502. errmsg = "keyword outside section";
  503. goto pe_label;
  504. }
  505. } /* while (1) */
  506. pe_label:
  507. fclose(f);
  508. bb_error_msg("parse error in %s, line %u: %s", config_file, lc, errmsg);
  509. /* Release any allocated memory before returning. */
  510. llist_free((llist_t*)sct_head, NULL);
  511. }
  512. # else
  513. static inline void parse_config_file(void)
  514. {
  515. IF_FEATURE_SUID(ruid = getuid();)
  516. }
  517. # endif /* FEATURE_SUID_CONFIG */
  518. # if ENABLE_FEATURE_SUID && NUM_APPLETS > 0
  519. # if ENABLE_FEATURE_SUID_CONFIG
  520. /* check if u is member of group g */
  521. static int ingroup(uid_t u, gid_t g)
  522. {
  523. struct group *grp = getgrgid(g);
  524. if (grp) {
  525. char **mem;
  526. for (mem = grp->gr_mem; *mem; mem++) {
  527. struct passwd *pwd = getpwnam(*mem);
  528. if (pwd && (pwd->pw_uid == u))
  529. return 1;
  530. }
  531. }
  532. return 0;
  533. }
  534. # endif
  535. static void check_suid(int applet_no)
  536. {
  537. gid_t rgid; /* real gid */
  538. if (ruid == 0) /* set by parse_config_file() */
  539. return; /* run by root - no need to check more */
  540. rgid = getgid();
  541. # if ENABLE_FEATURE_SUID_CONFIG
  542. if (suid_cfg_readable) {
  543. uid_t uid;
  544. struct suid_config_t *sct;
  545. mode_t m;
  546. for (sct = suid_config; sct; sct = sct->m_next) {
  547. if (sct->m_applet == applet_no)
  548. goto found;
  549. }
  550. goto check_need_suid;
  551. found:
  552. /* Is this user allowed to run this applet? */
  553. m = sct->m_mode;
  554. if (sct->m_ugid.uid == ruid)
  555. /* same uid */
  556. m >>= 6;
  557. else if ((sct->m_ugid.gid == rgid) || ingroup(ruid, sct->m_ugid.gid))
  558. /* same group / in group */
  559. m >>= 3;
  560. if (!(m & S_IXOTH)) /* is x bit not set? */
  561. bb_error_msg_and_die("you have no permission to run this applet");
  562. /* We set effective AND saved ids. If saved-id is not set
  563. * like we do below, seteuid(0) can still later succeed! */
  564. /* Are we directed to change gid
  565. * (APPLET = *s* USER.GROUP or APPLET = *S* USER.GROUP)?
  566. */
  567. if (sct->m_mode & S_ISGID)
  568. rgid = sct->m_ugid.gid;
  569. /* else: we will set egid = rgid, thus dropping sgid effect */
  570. if (setresgid(-1, rgid, rgid))
  571. bb_perror_msg_and_die("setresgid");
  572. /* Are we directed to change uid
  573. * (APPLET = s** USER.GROUP or APPLET = S** USER.GROUP)?
  574. */
  575. uid = ruid;
  576. if (sct->m_mode & S_ISUID)
  577. uid = sct->m_ugid.uid;
  578. /* else: we will set euid = ruid, thus dropping suid effect */
  579. if (setresuid(-1, uid, uid))
  580. bb_perror_msg_and_die("setresuid");
  581. goto ret;
  582. }
  583. # if !ENABLE_FEATURE_SUID_CONFIG_QUIET
  584. {
  585. static bool onetime = 0;
  586. if (!onetime) {
  587. onetime = 1;
  588. bb_error_msg("using fallback suid method");
  589. }
  590. }
  591. # endif
  592. check_need_suid:
  593. # endif
  594. if (APPLET_SUID(applet_no) == BB_SUID_REQUIRE) {
  595. /* Real uid is not 0. If euid isn't 0 too, suid bit
  596. * is most probably not set on our executable */
  597. if (geteuid())
  598. bb_error_msg_and_die("must be suid to work properly");
  599. } else if (APPLET_SUID(applet_no) == BB_SUID_DROP) {
  600. xsetgid(rgid); /* drop all privileges */
  601. xsetuid(ruid);
  602. }
  603. # if ENABLE_FEATURE_SUID_CONFIG
  604. ret: ;
  605. llist_free((llist_t*)suid_config, NULL);
  606. # endif
  607. }
  608. # else
  609. # define check_suid(x) ((void)0)
  610. # endif /* FEATURE_SUID */
  611. # if ENABLE_FEATURE_INSTALLER
  612. static const char usr_bin [] ALIGN1 = "/usr/bin/";
  613. static const char usr_sbin[] ALIGN1 = "/usr/sbin/";
  614. static const char *const install_dir[] = {
  615. &usr_bin [8], /* "/" */
  616. &usr_bin [4], /* "/bin/" */
  617. &usr_sbin[4] /* "/sbin/" */
  618. # if !ENABLE_INSTALL_NO_USR
  619. ,usr_bin
  620. ,usr_sbin
  621. # endif
  622. };
  623. /* create (sym)links for each applet */
  624. static void install_links(const char *busybox, int use_symbolic_links,
  625. char *custom_install_dir)
  626. {
  627. /* directory table
  628. * this should be consistent w/ the enum,
  629. * busybox.h::bb_install_loc_t, or else... */
  630. int (*lf)(const char *, const char *);
  631. char *fpc;
  632. const char *appname = applet_names;
  633. unsigned i;
  634. int rc;
  635. lf = link;
  636. if (use_symbolic_links)
  637. lf = symlink;
  638. for (i = 0; i < ARRAY_SIZE(applet_main); i++) {
  639. fpc = concat_path_file(
  640. custom_install_dir ? custom_install_dir : install_dir[APPLET_INSTALL_LOC(i)],
  641. appname);
  642. // debug: bb_error_msg("%slinking %s to busybox",
  643. // use_symbolic_links ? "sym" : "", fpc);
  644. rc = lf(busybox, fpc);
  645. if (rc != 0 && errno != EEXIST) {
  646. bb_simple_perror_msg(fpc);
  647. }
  648. free(fpc);
  649. while (*appname++ != '\0')
  650. continue;
  651. }
  652. }
  653. # elif ENABLE_BUSYBOX
  654. static void install_links(const char *busybox UNUSED_PARAM,
  655. int use_symbolic_links UNUSED_PARAM,
  656. char *custom_install_dir UNUSED_PARAM)
  657. {
  658. }
  659. # endif
  660. # if ENABLE_BUSYBOX
  661. static void run_applet_and_exit(const char *name, char **argv) NORETURN;
  662. /* If we were called as "busybox..." */
  663. static int busybox_main(char **argv)
  664. {
  665. if (!argv[1]) {
  666. /* Called without arguments */
  667. const char *a;
  668. int col;
  669. unsigned output_width;
  670. help:
  671. output_width = get_terminal_width(2);
  672. dup2(1, 2);
  673. full_write2_str(bb_banner); /* reuse const string */
  674. full_write2_str(" multi-call binary.\n"); /* reuse */
  675. full_write2_str(
  676. "BusyBox is copyrighted by many authors between 1998-2015.\n"
  677. "Licensed under GPLv2. See source distribution for detailed\n"
  678. "copyright notices.\n"
  679. "\n"
  680. "Usage: busybox [function [arguments]...]\n"
  681. " or: busybox --list"IF_FEATURE_INSTALLER("[-full]")"\n"
  682. IF_FEATURE_INSTALLER(
  683. " or: busybox --install [-s] [DIR]\n"
  684. )
  685. " or: function [arguments]...\n"
  686. "\n"
  687. IF_NOT_FEATURE_SH_STANDALONE(
  688. "\tBusyBox is a multi-call binary that combines many common Unix\n"
  689. "\tutilities into a single executable. Most people will create a\n"
  690. "\tlink to busybox for each function they wish to use and BusyBox\n"
  691. "\twill act like whatever it was invoked as.\n"
  692. )
  693. IF_FEATURE_SH_STANDALONE(
  694. "\tBusyBox is a multi-call binary that combines many common Unix\n"
  695. "\tutilities into a single executable. The shell in this build\n"
  696. "\tis configured to run built-in utilities without $PATH search.\n"
  697. "\tYou don't need to install a link to busybox for each utility.\n"
  698. "\tTo run external program, use full path (/sbin/ip instead of ip).\n"
  699. )
  700. "\n"
  701. "Currently defined functions:\n"
  702. );
  703. col = 0;
  704. a = applet_names;
  705. /* prevent last comma to be in the very last pos */
  706. output_width--;
  707. while (*a) {
  708. int len2 = strlen(a) + 2;
  709. if (col >= (int)output_width - len2) {
  710. full_write2_str(",\n");
  711. col = 0;
  712. }
  713. if (col == 0) {
  714. col = 6;
  715. full_write2_str("\t");
  716. } else {
  717. full_write2_str(", ");
  718. }
  719. full_write2_str(a);
  720. col += len2;
  721. a += len2 - 1;
  722. }
  723. full_write2_str("\n");
  724. return 0;
  725. }
  726. if (is_prefixed_with(argv[1], "--list")) {
  727. unsigned i = 0;
  728. const char *a = applet_names;
  729. dup2(1, 2);
  730. while (*a) {
  731. # if ENABLE_FEATURE_INSTALLER
  732. if (argv[1][6]) /* --list-full? */
  733. full_write2_str(install_dir[APPLET_INSTALL_LOC(i)] + 1);
  734. # endif
  735. full_write2_str(a);
  736. full_write2_str("\n");
  737. i++;
  738. while (*a++ != '\0')
  739. continue;
  740. }
  741. return 0;
  742. }
  743. if (ENABLE_FEATURE_INSTALLER && strcmp(argv[1], "--install") == 0) {
  744. int use_symbolic_links;
  745. const char *busybox;
  746. busybox = xmalloc_readlink(bb_busybox_exec_path);
  747. if (!busybox) {
  748. /* bb_busybox_exec_path is usually "/proc/self/exe".
  749. * In chroot, readlink("/proc/self/exe") usually fails.
  750. * In such case, better use argv[0] as symlink target
  751. * if it is a full path name.
  752. */
  753. if (argv[0][0] != '/')
  754. bb_error_msg_and_die("'%s' is not an absolute path", argv[0]);
  755. busybox = argv[0];
  756. }
  757. /* busybox --install [-s] [DIR]:
  758. * -s: make symlinks
  759. * DIR: directory to install links to
  760. */
  761. use_symbolic_links = (argv[2] && strcmp(argv[2], "-s") == 0 && ++argv);
  762. install_links(busybox, use_symbolic_links, argv[2]);
  763. return 0;
  764. }
  765. if (strcmp(argv[1], "--help") == 0) {
  766. /* "busybox --help [<applet>]" */
  767. if (!argv[2])
  768. goto help;
  769. /* convert to "<applet> --help" */
  770. argv[0] = argv[2];
  771. argv[2] = NULL;
  772. } else {
  773. /* "busybox <applet> arg1 arg2 ..." */
  774. argv++;
  775. }
  776. /* We support "busybox /a/path/to/applet args..." too. Allows for
  777. * "#!/bin/busybox"-style wrappers */
  778. applet_name = bb_get_last_path_component_nostrip(argv[0]);
  779. run_applet_and_exit(applet_name, argv);
  780. }
  781. # endif
  782. # if NUM_APPLETS > 0
  783. void FAST_FUNC run_applet_no_and_exit(int applet_no, const char *name, char **argv)
  784. {
  785. int argc = string_array_len(argv);
  786. /* Reinit some shared global data */
  787. xfunc_error_retval = EXIT_FAILURE;
  788. /*
  789. * We do not use argv[0]: do not want to repeat massaging of
  790. * "-/sbin/halt" -> "halt", for example.
  791. */
  792. applet_name = name;
  793. /* Special case. POSIX says "test --help"
  794. * should be no different from e.g. "test --foo".
  795. * Thus for "test", we skip --help check.
  796. * "true" and "false" are also special.
  797. */
  798. if (1
  799. # if defined APPLET_NO_test
  800. && applet_no != APPLET_NO_test
  801. # endif
  802. # if defined APPLET_NO_true
  803. && applet_no != APPLET_NO_true
  804. # endif
  805. # if defined APPLET_NO_false
  806. && applet_no != APPLET_NO_false
  807. # endif
  808. ) {
  809. if (argc == 2 && strcmp(argv[1], "--help") == 0) {
  810. /* Make "foo --help" exit with 0: */
  811. xfunc_error_retval = 0;
  812. bb_show_usage();
  813. }
  814. }
  815. if (ENABLE_FEATURE_SUID)
  816. check_suid(applet_no);
  817. xfunc_error_retval = applet_main[applet_no](argc, argv);
  818. /* Note: applet_main() may also not return (die on a xfunc or such) */
  819. xfunc_die();
  820. }
  821. # endif /* NUM_APPLETS > 0 */
  822. # if ENABLE_BUSYBOX || NUM_APPLETS > 0
  823. static NORETURN void run_applet_and_exit(const char *name, char **argv)
  824. {
  825. # if ENABLE_BUSYBOX
  826. if (is_prefixed_with(name, "busybox"))
  827. exit(busybox_main(argv));
  828. # endif
  829. # if NUM_APPLETS > 0
  830. /* find_applet_by_name() search is more expensive, so goes second */
  831. {
  832. int applet = find_applet_by_name(name);
  833. if (applet >= 0)
  834. run_applet_no_and_exit(applet, name, argv);
  835. }
  836. # endif
  837. /*bb_error_msg_and_die("applet not found"); - links in printf */
  838. full_write2_str(applet_name);
  839. full_write2_str(": applet not found\n");
  840. /* POSIX: "If a command is not found, the exit status shall be 127" */
  841. exit(127);
  842. }
  843. # endif
  844. #endif /* !defined(SINGLE_APPLET_MAIN) */
  845. #if ENABLE_BUILD_LIBBUSYBOX
  846. int lbb_main(char **argv)
  847. #else
  848. int main(int argc UNUSED_PARAM, char **argv)
  849. #endif
  850. {
  851. #if 0
  852. /* TODO: find a use for a block of memory between end of .bss
  853. * and end of page. For example, I'm getting "_end:0x812e698 2408 bytes"
  854. * - more than 2k of wasted memory (in this particular build)
  855. * *per each running process*!
  856. * (If your linker does not generate "_end" name, weak attribute
  857. * makes &_end == NULL, end_len == 0 here.)
  858. */
  859. extern char _end[] __attribute__((weak));
  860. unsigned end_len = (-(int)_end) & 0xfff;
  861. printf("_end:%p %u bytes\n", &_end, end_len);
  862. #endif
  863. /* Tweak malloc for reduced memory consumption */
  864. #ifdef M_TRIM_THRESHOLD
  865. /* M_TRIM_THRESHOLD is the maximum amount of freed top-most memory
  866. * to keep before releasing to the OS
  867. * Default is way too big: 256k
  868. */
  869. mallopt(M_TRIM_THRESHOLD, 8 * 1024);
  870. #endif
  871. #ifdef M_MMAP_THRESHOLD
  872. /* M_MMAP_THRESHOLD is the request size threshold for using mmap()
  873. * Default is too big: 256k
  874. */
  875. mallopt(M_MMAP_THRESHOLD, 32 * 1024 - 256);
  876. #endif
  877. #if 0 /*def M_TOP_PAD*/
  878. /* When the program break is increased, then M_TOP_PAD bytes are added
  879. * to the sbrk(2) request. When the heap is trimmed because of free(3),
  880. * this much free space is preserved at the top of the heap.
  881. * glibc default seems to be way too big: 128k, but need to verify.
  882. */
  883. mallopt(M_TOP_PAD, 8 * 1024);
  884. #endif
  885. #if !BB_MMU
  886. /* NOMMU re-exec trick sets high-order bit in first byte of name */
  887. if (argv[0][0] & 0x80) {
  888. re_execed = 1;
  889. argv[0][0] &= 0x7f;
  890. }
  891. #endif
  892. #if defined(SINGLE_APPLET_MAIN)
  893. /* Only one applet is selected in .config */
  894. if (argv[1] && is_prefixed_with(argv[0], "busybox")) {
  895. /* "busybox <applet> <params>" should still work as expected */
  896. argv++;
  897. }
  898. /* applet_names in this case is just "applet\0\0" */
  899. lbb_prepare(applet_names IF_FEATURE_INDIVIDUAL(, argv));
  900. # if ENABLE_BUILD_LIBBUSYBOX
  901. return SINGLE_APPLET_MAIN(string_array_len(argv), argv);
  902. # else
  903. return SINGLE_APPLET_MAIN(argc, argv);
  904. # endif
  905. #elif !ENABLE_BUSYBOX && NUM_APPLETS == 0
  906. full_write2_str(bb_basename(argv[0]));
  907. full_write2_str(": no applets enabled\n");
  908. exit(127);
  909. #else
  910. lbb_prepare("busybox" IF_FEATURE_INDIVIDUAL(, argv));
  911. # if !ENABLE_BUSYBOX
  912. if (argv[1] && is_prefixed_with(bb_basename(argv[0]), "busybox"))
  913. argv++;
  914. # endif
  915. applet_name = argv[0];
  916. if (applet_name[0] == '-')
  917. applet_name++;
  918. applet_name = bb_basename(applet_name);
  919. parse_config_file(); /* ...maybe, if FEATURE_SUID_CONFIG */
  920. run_applet_and_exit(applet_name, argv);
  921. #endif
  922. }