appletlib.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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 link 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");
  112. } else {
  113. full_write2_str("Usage: "SINGLE_APPLET_STR" ");
  114. full_write2_str(usage_string);
  115. full_write2_str("\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"); /* common string */
  132. if (*p == '\b')
  133. full_write2_str("\nNo help available\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) MAIN_EXTERNALLY_VISIBLE;
  684. int scripted_main(int argc UNUSED_PARAM, char **argv)
  685. {
  686. int script = find_script_by_name(applet_name);
  687. if (script >= 0)
  688. #if ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH
  689. exit(ash_main(-script - 1, argv));
  690. #elif ENABLE_HUSH || ENABLE_SH_IS_HUSH || ENABLE_BASH_IS_HUSH
  691. exit(hush_main(-script - 1, argv));
  692. #else
  693. return 1;
  694. #endif
  695. return 0;
  696. }
  697. char* FAST_FUNC
  698. get_script_content(unsigned n)
  699. {
  700. char *t = unpack_bz2_data(packed_scripts, sizeof(packed_scripts),
  701. UNPACKED_SCRIPTS_LENGTH);
  702. if (t) {
  703. while (n != 0) {
  704. while (*t++ != '\0')
  705. continue;
  706. n--;
  707. }
  708. }
  709. return t;
  710. }
  711. # endif /* NUM_SCRIPTS > 0 */
  712. # if ENABLE_BUSYBOX
  713. # if ENABLE_FEATURE_SH_STANDALONE && ENABLE_FEATURE_TAB_COMPLETION
  714. /*
  715. * Insert "busybox" into applet table as well.
  716. * This makes standalone shell tab-complete this name too.
  717. * (Otherwise having "busybox" in applet table is not necessary,
  718. * there is other code which routes "busyboxANY_SUFFIX" name
  719. * to busybox_main()).
  720. */
  721. //usage:#define busybox_trivial_usage NOUSAGE_STR
  722. //usage:#define busybox_full_usage ""
  723. //applet:IF_BUSYBOX(IF_FEATURE_SH_STANDALONE(IF_FEATURE_TAB_COMPLETION(APPLET(busybox, BB_DIR_BIN, BB_SUID_MAYBE))))
  724. int busybox_main(int argc, char *argv[]) MAIN_EXTERNALLY_VISIBLE;
  725. # else
  726. # define busybox_main(argc,argv) busybox_main(argv)
  727. static
  728. # endif
  729. int busybox_main(int argc UNUSED_PARAM, char **argv)
  730. {
  731. if (!argv[1]) {
  732. /* Called without arguments */
  733. const char *a;
  734. int col;
  735. unsigned output_width;
  736. help:
  737. output_width = get_terminal_width(2);
  738. dup2(1, 2);
  739. full_write2_str(bb_banner); /* reuse const string */
  740. full_write2_str(" multi-call binary.\n"); /* reuse */
  741. full_write2_str(
  742. "BusyBox is copyrighted by many authors between 1998-2015.\n"
  743. "Licensed under GPLv2. See source distribution for detailed\n"
  744. "copyright notices.\n"
  745. "\n"
  746. "Usage: busybox [function [arguments]...]\n"
  747. " or: busybox --list"IF_FEATURE_INSTALLER("[-full]")"\n"
  748. # if ENABLE_FEATURE_SHOW_SCRIPT && NUM_SCRIPTS > 0
  749. " or: busybox --show SCRIPT\n"
  750. # endif
  751. IF_FEATURE_INSTALLER(
  752. " or: busybox --install [-s] [DIR]\n"
  753. )
  754. " or: function [arguments]...\n"
  755. "\n"
  756. IF_NOT_FEATURE_SH_STANDALONE(
  757. "\tBusyBox is a multi-call binary that combines many common Unix\n"
  758. "\tutilities into a single executable. Most people will create a\n"
  759. "\tlink to busybox for each function they wish to use and BusyBox\n"
  760. "\twill act like whatever it was invoked as.\n"
  761. )
  762. IF_FEATURE_SH_STANDALONE(
  763. "\tBusyBox is a multi-call binary that combines many common Unix\n"
  764. "\tutilities into a single executable. The shell in this build\n"
  765. "\tis configured to run built-in utilities without $PATH search.\n"
  766. "\tYou don't need to install a link to busybox for each utility.\n"
  767. "\tTo run external program, use full path (/sbin/ip instead of ip).\n"
  768. )
  769. "\n"
  770. "Currently defined functions:\n"
  771. );
  772. col = 0;
  773. /* prevent last comma to be in the very last pos */
  774. output_width--;
  775. a = applet_names;
  776. while (*a) {
  777. int len2 = strlen(a) + 2;
  778. if (col >= (int)output_width - len2) {
  779. full_write2_str(",\n");
  780. col = 0;
  781. }
  782. if (col == 0) {
  783. col = 6;
  784. full_write2_str("\t");
  785. } else {
  786. full_write2_str(", ");
  787. }
  788. full_write2_str(a);
  789. col += len2;
  790. a += len2 - 1;
  791. }
  792. full_write2_str("\n");
  793. return 0;
  794. }
  795. # if ENABLE_FEATURE_SHOW_SCRIPT && NUM_SCRIPTS > 0
  796. if (strcmp(argv[1], "--show") == 0) {
  797. int n;
  798. if (!argv[2])
  799. bb_error_msg_and_die(bb_msg_requires_arg, "--show");
  800. n = find_script_by_name(argv[2]);
  801. if (n < 0)
  802. bb_error_msg_and_die("script '%s' not found", argv[2]);
  803. full_write1_str(get_script_content(n));
  804. return 0;
  805. }
  806. # endif
  807. if (is_prefixed_with(argv[1], "--list")) {
  808. unsigned i = 0;
  809. const char *a = applet_names;
  810. dup2(1, 2);
  811. while (*a) {
  812. # if ENABLE_FEATURE_INSTALLER
  813. if (argv[1][6]) /* --list-full? */
  814. full_write2_str(install_dir[APPLET_INSTALL_LOC(i)] + 1);
  815. # endif
  816. full_write2_str(a);
  817. full_write2_str("\n");
  818. i++;
  819. while (*a++ != '\0')
  820. continue;
  821. }
  822. return 0;
  823. }
  824. if (ENABLE_FEATURE_INSTALLER && strcmp(argv[1], "--install") == 0) {
  825. int use_symbolic_links;
  826. const char *busybox;
  827. busybox = xmalloc_readlink(bb_busybox_exec_path);
  828. if (!busybox) {
  829. /* bb_busybox_exec_path is usually "/proc/self/exe".
  830. * In chroot, readlink("/proc/self/exe") usually fails.
  831. * In such case, better use argv[0] as symlink target
  832. * if it is a full path name.
  833. */
  834. if (argv[0][0] != '/')
  835. bb_error_msg_and_die("'%s' is not an absolute path", argv[0]);
  836. busybox = argv[0];
  837. }
  838. /* busybox --install [-s] [DIR]:
  839. * -s: make symlinks
  840. * DIR: directory to install links to
  841. */
  842. use_symbolic_links = (argv[2] && strcmp(argv[2], "-s") == 0 && ++argv);
  843. install_links(busybox, use_symbolic_links, argv[2]);
  844. return 0;
  845. }
  846. if (strcmp(argv[1], "--help") == 0) {
  847. /* "busybox --help [<applet>]" */
  848. if (!argv[2])
  849. goto help;
  850. /* convert to "<applet> --help" */
  851. argv[0] = argv[2];
  852. argv[2] = NULL;
  853. } else {
  854. /* "busybox <applet> arg1 arg2 ..." */
  855. argv++;
  856. }
  857. /* We support "busybox /a/path/to/applet args..." too. Allows for
  858. * "#!/bin/busybox"-style wrappers */
  859. applet_name = bb_get_last_path_component_nostrip(argv[0]);
  860. run_applet_and_exit(applet_name, argv);
  861. }
  862. # endif
  863. # if NUM_APPLETS > 0
  864. void FAST_FUNC run_applet_no_and_exit(int applet_no, const char *name, char **argv)
  865. {
  866. int argc = string_array_len(argv);
  867. /*
  868. * We do not use argv[0]: do not want to repeat massaging of
  869. * "-/sbin/halt" -> "halt", for example.
  870. */
  871. applet_name = name;
  872. /* Special case. POSIX says "test --help"
  873. * should be no different from e.g. "test --foo".
  874. * Thus for "test", we skip --help check.
  875. * "true" and "false" are also special.
  876. */
  877. if (1
  878. # if defined APPLET_NO_test
  879. && applet_no != APPLET_NO_test
  880. # endif
  881. # if defined APPLET_NO_true
  882. && applet_no != APPLET_NO_true
  883. # endif
  884. # if defined APPLET_NO_false
  885. && applet_no != APPLET_NO_false
  886. # endif
  887. ) {
  888. if (argc == 2 && strcmp(argv[1], "--help") == 0) {
  889. /* Make "foo --help" exit with 0: */
  890. xfunc_error_retval = 0;
  891. bb_show_usage();
  892. }
  893. }
  894. if (ENABLE_FEATURE_SUID)
  895. check_suid(applet_no);
  896. xfunc_error_retval = applet_main[applet_no](argc, argv);
  897. /* Note: applet_main() may also not return (die on a xfunc or such) */
  898. xfunc_die();
  899. }
  900. # endif /* NUM_APPLETS > 0 */
  901. # if ENABLE_BUSYBOX || NUM_APPLETS > 0
  902. static NORETURN void run_applet_and_exit(const char *name, char **argv)
  903. {
  904. # if ENABLE_BUSYBOX
  905. if (is_prefixed_with(name, "busybox"))
  906. exit(busybox_main(/*unused:*/ 0, argv));
  907. # endif
  908. # if NUM_APPLETS > 0
  909. /* find_applet_by_name() search is more expensive, so goes second */
  910. {
  911. int applet = find_applet_by_name(name);
  912. if (applet >= 0)
  913. run_applet_no_and_exit(applet, name, argv);
  914. }
  915. # endif
  916. /*bb_error_msg_and_die("applet not found"); - links in printf */
  917. full_write2_str(applet_name);
  918. full_write2_str(": applet not found\n");
  919. /* POSIX: "If a command is not found, the exit status shall be 127" */
  920. exit(127);
  921. }
  922. # endif
  923. #endif /* !defined(SINGLE_APPLET_MAIN) */
  924. #if ENABLE_BUILD_LIBBUSYBOX
  925. int lbb_main(char **argv)
  926. #else
  927. int main(int argc UNUSED_PARAM, char **argv)
  928. #endif
  929. {
  930. #if 0
  931. /* TODO: find a use for a block of memory between end of .bss
  932. * and end of page. For example, I'm getting "_end:0x812e698 2408 bytes"
  933. * - more than 2k of wasted memory (in this particular build)
  934. * *per each running process*!
  935. * (If your linker does not generate "_end" name, weak attribute
  936. * makes &_end == NULL, end_len == 0 here.)
  937. */
  938. extern char _end[] __attribute__((weak));
  939. unsigned end_len = (-(int)_end) & 0xfff;
  940. printf("_end:%p %u bytes\n", &_end, end_len);
  941. #endif
  942. /* Tweak malloc for reduced memory consumption */
  943. #ifdef M_TRIM_THRESHOLD
  944. /* M_TRIM_THRESHOLD is the maximum amount of freed top-most memory
  945. * to keep before releasing to the OS
  946. * Default is way too big: 256k
  947. */
  948. mallopt(M_TRIM_THRESHOLD, 8 * 1024);
  949. #endif
  950. #ifdef M_MMAP_THRESHOLD
  951. /* M_MMAP_THRESHOLD is the request size threshold for using mmap()
  952. * Default is too big: 256k
  953. */
  954. mallopt(M_MMAP_THRESHOLD, 32 * 1024 - 256);
  955. #endif
  956. #if 0 /*def M_TOP_PAD*/
  957. /* When the program break is increased, then M_TOP_PAD bytes are added
  958. * to the sbrk(2) request. When the heap is trimmed because of free(3),
  959. * this much free space is preserved at the top of the heap.
  960. * glibc default seems to be way too big: 128k, but need to verify.
  961. */
  962. mallopt(M_TOP_PAD, 8 * 1024);
  963. #endif
  964. #if !BB_MMU
  965. /* NOMMU re-exec trick sets high-order bit in first byte of name */
  966. if (argv[0][0] & 0x80) {
  967. re_execed = 1;
  968. argv[0][0] &= 0x7f;
  969. }
  970. #endif
  971. #if defined(SINGLE_APPLET_MAIN)
  972. /* Only one applet is selected in .config */
  973. if (argv[1] && is_prefixed_with(argv[0], "busybox")) {
  974. /* "busybox <applet> <params>" should still work as expected */
  975. argv++;
  976. }
  977. /* applet_names in this case is just "applet\0\0" */
  978. lbb_prepare(applet_names IF_FEATURE_INDIVIDUAL(, argv));
  979. # if ENABLE_BUILD_LIBBUSYBOX
  980. return SINGLE_APPLET_MAIN(string_array_len(argv), argv);
  981. # else
  982. return SINGLE_APPLET_MAIN(argc, argv);
  983. # endif
  984. #elif !ENABLE_BUSYBOX && NUM_APPLETS == 0
  985. full_write2_str(bb_basename(argv[0]));
  986. full_write2_str(": no applets enabled\n");
  987. exit(127);
  988. #else
  989. lbb_prepare("busybox" IF_FEATURE_INDIVIDUAL(, argv));
  990. # if !ENABLE_BUSYBOX
  991. if (argv[1] && is_prefixed_with(bb_basename(argv[0]), "busybox"))
  992. argv++;
  993. # endif
  994. applet_name = argv[0];
  995. if (applet_name[0] == '-')
  996. applet_name++;
  997. applet_name = bb_basename(applet_name);
  998. /* If we are a result of execv("/proc/self/exe"), fix ugly comm of "exe" */
  999. if (ENABLE_FEATURE_SH_STANDALONE
  1000. || ENABLE_FEATURE_PREFER_APPLETS
  1001. || !BB_MMU
  1002. ) {
  1003. if (NUM_APPLETS > 1)
  1004. set_task_comm(applet_name);
  1005. }
  1006. parse_config_file(); /* ...maybe, if FEATURE_SUID_CONFIG */
  1007. run_applet_and_exit(applet_name, argv);
  1008. #endif
  1009. }