appletlib.c 25 KB

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