appletlib.c 30 KB

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