appletlib.c 30 KB

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