3
0

appletlib.c 31 KB

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