appletlib.c 29 KB

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