appletlib.c 31 KB

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