appletlib.c 31 KB

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