appletlib.c 29 KB

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