1 /* vi: set sw=4 ts=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.
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.
12 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
15 /* We are trying to not use printf, this benefits the case when selected
16 * applets are really simple. Example:
20 * Currently defined functions:
21 * basename, false, true
24 * text data bss dec hex filename
25 * 4473 52 72 4597 11f5 busybox
27 * FEATURE_INSTALLER or FEATURE_SUID will still link printf routines in. :(
32 /* Try to pull in PAGE_SIZE */
34 # include <sys/user.h>
36 #ifdef __GNU__ /* Hurd */
37 # include <mach/vm_param.h>
41 /* Declare <applet>_main() */
47 /* Include generated applet names, pointers to <applet>_main, etc */
48 #include "applet_tables.h"
49 /* ...and if applet_tables generator says we have only one applet... */
50 #ifdef SINGLE_APPLET_MAIN
51 # undef ENABLE_FEATURE_INDIVIDUAL
52 # define ENABLE_FEATURE_INDIVIDUAL 1
53 # undef IF_FEATURE_INDIVIDUAL
54 # define IF_FEATURE_INDIVIDUAL(...) __VA_ARGS__
58 #include "usage_compressed.h"
60 #if ENABLE_SHOW_USAGE && !ENABLE_FEATURE_COMPRESS_USAGE
61 static const char usage_messages[] ALIGN1 = UNPACKED_USAGE;
63 # define usage_messages 0
66 #if ENABLE_FEATURE_COMPRESS_USAGE
68 static const char packed_usage[] ALIGN1 = { PACKED_USAGE };
70 static const char *unpack_usage_messages(void)
78 /* inbuf: */ packed_usage,
79 /* len: */ sizeof(packed_usage));
80 /* read_bunzip can longjmp to start_bunzip, and ultimately
81 * end up here with i != 0 on read data errors! Not trivial */
83 /* Cannot use xmalloc: will leak bd in NOFORK case! */
84 outbuf = malloc_or_warn(sizeof(UNPACKED_USAGE));
86 read_bunzip(bd, outbuf, sizeof(UNPACKED_USAGE));
91 # define dealloc_usage_messages(s) free(s)
95 # define unpack_usage_messages() usage_messages
96 # define dealloc_usage_messages(s) ((void)(s))
98 #endif /* FEATURE_COMPRESS_USAGE */
101 void FAST_FUNC bb_show_usage(void)
103 if (ENABLE_SHOW_USAGE) {
104 #ifdef SINGLE_APPLET_STR
105 /* Imagine that this applet is "true". Dont suck in printf! */
106 const char *usage_string = unpack_usage_messages();
108 if (*usage_string == '\b') {
109 full_write2_str("No help available.\n\n");
111 full_write2_str("Usage: "SINGLE_APPLET_STR" ");
112 full_write2_str(usage_string);
113 full_write2_str("\n\n");
115 if (ENABLE_FEATURE_CLEAN_UP)
116 dealloc_usage_messages((char*)usage_string);
119 const char *usage_string = p = unpack_usage_messages();
120 int ap = find_applet_by_name(applet_name);
122 if (ap < 0) /* never happens, paranoia */
125 while (*p++) continue;
128 full_write2_str(bb_banner);
129 full_write2_str(" multi-call binary.\n");
131 full_write2_str("\nNo help available.\n\n");
133 full_write2_str("\nUsage: ");
134 full_write2_str(applet_name);
135 full_write2_str(" ");
137 full_write2_str("\n\n");
139 if (ENABLE_FEATURE_CLEAN_UP)
140 dealloc_usage_messages((char*)usage_string);
147 /* NB: any char pointer will work as well, not necessarily applet_names */
148 static int applet_name_compare(const void *name, const void *v)
150 int i = (const char *)v - applet_names;
151 return strcmp(name, APPLET_NAME(i));
154 int FAST_FUNC find_applet_by_name(const char *name)
157 /* Do a binary search to find the applet entry given the name. */
159 p = bsearch(name, applet_names, ARRAY_SIZE(applet_main), 1, applet_name_compare);
162 return p - applet_names;
164 /* A version which does not pull in bsearch */
166 const char *p = applet_names;
167 while (i < NUM_APPLETS) {
168 if (strcmp(name, p) == 0)
178 void lbb_prepare(const char *applet
179 IF_FEATURE_INDIVIDUAL(, char **argv))
180 MAIN_EXTERNALLY_VISIBLE;
181 void lbb_prepare(const char *applet
182 IF_FEATURE_INDIVIDUAL(, char **argv))
185 (*(int **)&bb_errno) = __errno_location();
188 applet_name = applet;
190 /* Set locale for everybody except 'init' */
191 if (ENABLE_LOCALE_SUPPORT && getpid() != 1)
192 setlocale(LC_ALL, "");
194 #if ENABLE_FEATURE_INDIVIDUAL
195 /* Redundant for busybox (run_applet_and_exit covers that case)
196 * but needed for "individual applet" mode */
199 && strcmp(argv[1], "--help") == 0
200 && strncmp(applet, "busybox", 7) != 0
202 /* Special case. POSIX says "test --help"
203 * should be no different from e.g. "test --foo". */
204 if (!ENABLE_TEST || strcmp(applet_name, "test") != 0)
210 /* The code below can well be in applets/applets.c, as it is used only
211 * for busybox binary, not "individual" binaries.
212 * However, keeping it here and linking it into libbusybox.so
213 * (together with remaining tiny applets/applets.o)
214 * makes it possible to avoid --whole-archive at link time.
215 * This makes (shared busybox) + libbusybox smaller.
216 * (--gc-sections would be even better....)
219 const char *applet_name;
225 /* If not built as a single-applet executable... */
226 #if !defined(SINGLE_APPLET_MAIN)
228 IF_FEATURE_SUID(static uid_t ruid;) /* real uid */
230 # if ENABLE_FEATURE_SUID_CONFIG
232 /* applets[] is const, so we have to define this "override" structure */
233 static struct BB_suid_config {
238 struct BB_suid_config *m_next;
241 static bool suid_cfg_readable;
243 /* check if u is member of group g */
244 static int ingroup(uid_t u, gid_t g)
246 struct group *grp = getgrgid(g);
251 for (mem = grp->gr_mem; *mem; mem++) {
252 struct passwd *pwd = getpwnam(*mem);
254 if (pwd && (pwd->pw_uid == u))
261 /* This should probably be a libbb routine. In that case,
262 * I'd probably rename it to something like bb_trimmed_slice.
264 static char *get_trimmed_slice(char *s, char *e)
266 /* First, consider the value at e to be nul and back up until we
267 * reach a non-space char. Set the char after that (possibly at
268 * the original e) to nul. */
276 /* Next, advance past all leading space and return a ptr to the
277 * first non-space char; possibly the terminating nul. */
278 return skip_whitespace(s);
281 /* Don't depend on the tools to combine strings. */
282 static const char config_file[] ALIGN1 = "/etc/busybox.conf";
284 /* We don't supply a value for the nul, so an index adjustment is
285 * necessary below. Also, we use unsigned short here to save some
286 * space even though these are really mode_t values. */
287 static const unsigned short mode_mask[] ALIGN2 = {
288 /* SST sst xxx --- */
289 S_ISUID, S_ISUID|S_IXUSR, S_IXUSR, 0, /* user */
290 S_ISGID, S_ISGID|S_IXGRP, S_IXGRP, 0, /* group */
291 0, S_IXOTH, S_IXOTH, 0 /* other */
294 #define parse_error(x) do { errmsg = x; goto pe_label; } while (0)
296 static void parse_config_file(void)
298 struct BB_suid_config *sct_head;
299 struct BB_suid_config *sct;
311 assert(!suid_config); /* Should be set to NULL by bss init. */
314 if (ruid == 0) /* run by root - don't need to even read config file */
317 if ((stat(config_file, &st) != 0) /* No config file? */
318 || !S_ISREG(st.st_mode) /* Not a regular file? */
319 || (st.st_uid != 0) /* Not owned by root? */
320 || (st.st_mode & (S_IWGRP | S_IWOTH)) /* Writable by non-root? */
321 || !(f = fopen_for_read(config_file)) /* Cannot open? */
326 suid_cfg_readable = 1;
333 if (!fgets(s, sizeof(buffer), f)) { /* Are we done? */
335 if (ferror(f)) { /* Make sure it wasn't a read error. */
336 parse_error("reading");
339 suid_config = sct_head; /* Success, so set the pointer. */
343 lc++; /* Got a (partial) line. */
345 /* If a line is too long for our buffer, we consider it an error.
346 * The following test does mistreat one corner case though.
347 * If the final line of the file does not end with a newline and
348 * yet exactly fills the buffer, it will be treated as too long
349 * even though there isn't really a problem. But it isn't really
350 * worth adding code to deal with such an unlikely situation, and
351 * we do err on the side of caution. Besides, the line would be
352 * too long if it did end with a newline. */
353 if (!strchr(s, '\n') && !feof(f)) {
354 parse_error("line too long");
357 /* Trim leading and trailing whitespace, ignoring comments, and
358 * check if the resulting string is empty. */
359 s = get_trimmed_slice(s, strchrnul(s, '#'));
364 /* Check for a section header. */
367 /* Unlike the old code, we ignore leading and trailing
368 * whitespace for the section name. We also require that
369 * there are no stray characters after the closing bracket. */
371 if (!e /* Missing right bracket? */
372 || e[1] /* Trailing characters? */
373 || !*(s = get_trimmed_slice(s+1, e)) /* Missing name? */
375 parse_error("section header");
377 /* Right now we only have one section so just check it.
378 * If more sections are added in the future, please don't
379 * resort to cascading ifs with multiple strcasecmp calls.
380 * That kind of bloated code is all too common. A loop
381 * and a string table would be a better choice unless the
382 * number of sections is very small. */
383 if (strcasecmp(s, "SUID") == 0) {
387 section = -1; /* Unknown section so set to skip. */
391 /* Process sections. */
393 if (section == 1) { /* SUID */
394 /* Since we trimmed leading and trailing space above, we're
395 * now looking for strings of the form
396 * <key>[::space::]*=[::space::]*<value>
397 * where both key and value could contain inner whitespace. */
399 /* First get the key (an applet name in our case). */
402 s = get_trimmed_slice(s, e);
404 if (!e || !*s) { /* Missing '=' or empty key. */
405 parse_error("keyword");
408 /* Ok, we have an applet name. Process the rhs if this
409 * applet is currently built in and ignore it otherwise.
410 * Note: this can hide config file bugs which only pop
411 * up when the busybox configuration is changed. */
412 applet_no = find_applet_by_name(s);
413 if (applet_no >= 0) {
414 /* Note: We currently don't check for duplicates!
415 * The last config line for each applet will be the
416 * one used since we insert at the head of the list.
417 * I suppose this could be considered a feature. */
418 sct = xmalloc(sizeof(struct BB_suid_config));
419 sct->m_applet = applet_no;
421 sct->m_next = sct_head;
424 /* Get the specified mode. */
426 e = skip_whitespace(e+1);
428 for (i = 0; i < 3; i++) {
429 /* There are 4 chars + 1 nul for each of user/group/other. */
430 static const char mode_chars[] ALIGN1 = "Ssx-\0" "Ssx-\0" "Ttx-";
433 q = strchrnul(mode_chars + 5*i, *e++);
437 /* Adjust by -i to account for nul. */
438 sct->m_mode |= mode_mask[(q - mode_chars) - i];
441 /* Now get the the user/group info. */
443 s = skip_whitespace(e);
445 /* Note: we require whitespace between the mode and the
446 * user/group info. */
447 if ((s == e) || !(e = strchr(s, '.'))) {
448 parse_error("<uid>.<gid>");
452 /* We can't use get_ug_id here since it would exit()
453 * if a uid or gid was not found. Oh well... */
454 sct->m_uid = bb_strtoul(s, NULL, 10);
456 struct passwd *pwd = getpwnam(s);
460 sct->m_uid = pwd->pw_uid;
463 sct->m_gid = bb_strtoul(e, NULL, 10);
468 parse_error("group");
470 sct->m_gid = grp->gr_gid;
476 /* Unknown sections are ignored. */
478 /* Encountering configuration lines prior to seeing a
479 * section header is treated as an error. This is how
480 * the old code worked, but it may not be desirable.
481 * We may want to simply ignore such lines in case they
482 * are used in some future version of busybox. */
484 parse_error("keyword outside section");
490 fprintf(stderr, "Parse error in %s, line %d: %s\n",
491 config_file, lc, errmsg);
494 /* Release any allocated memory before returning. */
496 sct = sct_head->m_next;
502 static inline void parse_config_file(void)
504 IF_FEATURE_SUID(ruid = getuid();)
506 # endif /* FEATURE_SUID_CONFIG */
509 # if ENABLE_FEATURE_SUID
510 static void check_suid(int applet_no)
512 gid_t rgid; /* real gid */
514 if (ruid == 0) /* set by parse_config_file() */
515 return; /* run by root - no need to check more */
518 # if ENABLE_FEATURE_SUID_CONFIG
519 if (suid_cfg_readable) {
521 struct BB_suid_config *sct;
524 for (sct = suid_config; sct; sct = sct->m_next) {
525 if (sct->m_applet == applet_no)
528 goto check_need_suid;
531 if (sct->m_uid == ruid)
534 else if ((sct->m_gid == rgid) || ingroup(ruid, sct->m_gid))
535 /* same group / in group */
538 if (!(m & S_IXOTH)) /* is x bit not set ? */
539 bb_error_msg_and_die("you have no permission to run this applet!");
541 /* _both_ sgid and group_exec have to be set for setegid */
542 if ((sct->m_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
544 /* else (no setegid) we will set egid = rgid */
546 /* We set effective AND saved ids. If saved-id is not set
547 * like we do below, seteiud(0) can still later succeed! */
548 if (setresgid(-1, rgid, rgid))
549 bb_perror_msg_and_die("setresgid");
551 /* do we have to set effective uid? */
553 if (sct->m_mode & S_ISUID)
555 /* else (no seteuid) we will set euid = ruid */
557 if (setresuid(-1, uid, uid))
558 bb_perror_msg_and_die("setresuid");
561 # if !ENABLE_FEATURE_SUID_CONFIG_QUIET
563 static bool onetime = 0;
567 fprintf(stderr, "Using fallback suid method\n");
573 if (APPLET_SUID(applet_no) == _BB_SUID_REQUIRE) {
574 /* Real uid is not 0. If euid isn't 0 too, suid bit
575 * is most probably not set on our executable */
577 bb_error_msg_and_die("must be suid to work properly");
578 } else if (APPLET_SUID(applet_no) == _BB_SUID_DROP) {
579 xsetgid(rgid); /* drop all privileges */
584 # define check_suid(x) ((void)0)
585 # endif /* FEATURE_SUID */
588 # if ENABLE_FEATURE_INSTALLER
589 static const char usr_bin [] ALIGN1 = "/usr/bin/";
590 static const char usr_sbin[] ALIGN1 = "/usr/sbin/";
591 static const char *const install_dir[] = {
592 &usr_bin [8], /* "/" */
593 &usr_bin [4], /* "/bin/" */
594 &usr_sbin[4] /* "/sbin/" */
595 # if !ENABLE_INSTALL_NO_USR
601 /* create (sym)links for each applet */
602 static void install_links(const char *busybox, int use_symbolic_links,
603 char *custom_install_dir)
606 * this should be consistent w/ the enum,
607 * busybox.h::bb_install_loc_t, or else... */
608 int (*lf)(const char *, const char *);
614 if (use_symbolic_links)
617 for (i = 0; i < ARRAY_SIZE(applet_main); i++) {
618 fpc = concat_path_file(
619 custom_install_dir ? custom_install_dir : install_dir[APPLET_INSTALL_LOC(i)],
621 // debug: bb_error_msg("%slinking %s to busybox",
622 // use_symbolic_links ? "sym" : "", fpc);
623 rc = lf(busybox, fpc);
624 if (rc != 0 && errno != EEXIST) {
625 bb_simple_perror_msg(fpc);
631 # define install_links(x,y,z) ((void)0)
634 /* If we were called as "busybox..." */
635 static int busybox_main(char **argv)
638 /* Called without arguments */
641 unsigned output_width;
644 if (ENABLE_FEATURE_AUTOWIDTH) {
645 /* Obtain the terminal width */
646 get_terminal_width_height(0, &output_width, NULL);
650 full_write2_str(bb_banner); /* reuse const string */
651 full_write2_str(" multi-call binary.\n"); /* reuse */
653 "Copyright (C) 1998-2009 Erik Andersen, Rob Landley, Denys Vlasenko\n"
654 "and others. Licensed under GPLv2.\n"
655 "See source distribution for full notice.\n"
657 "Usage: busybox [function] [arguments]...\n"
658 " or: busybox --list[-full]\n"
659 " or: function [arguments]...\n"
661 "\tBusyBox is a multi-call binary that combines many common Unix\n"
662 "\tutilities into a single executable. Most people will create a\n"
663 "\tlink to busybox for each function they wish to use and BusyBox\n"
664 "\twill act like whatever it was invoked as.\n"
666 "Currently defined functions:\n"
670 /* prevent last comma to be in the very last pos */
673 int len2 = strlen(a) + 2;
674 if (col >= (int)output_width - len2) {
675 full_write2_str(",\n");
680 full_write2_str("\t");
682 full_write2_str(", ");
688 full_write2_str("\n\n");
692 if (strncmp(argv[1], "--list", 6) == 0) {
694 const char *a = applet_names;
697 # if ENABLE_FEATURE_INSTALLER
698 if (argv[1][6]) /* --list-path? */
699 full_write2_str(install_dir[APPLET_INSTALL_LOC(i)] + 1);
702 full_write2_str("\n");
709 if (ENABLE_FEATURE_INSTALLER && strcmp(argv[1], "--install") == 0) {
710 int use_symbolic_links;
712 busybox = xmalloc_readlink(bb_busybox_exec_path);
714 busybox = bb_busybox_exec_path;
715 /* busybox --install [-s] [DIR]: */
716 /* -s: make symlinks */
717 /* DIR: directory to install links to */
718 use_symbolic_links = (argv[2] && strcmp(argv[2], "-s") == 0 && argv++);
719 install_links(busybox, use_symbolic_links, argv[2]);
723 if (strcmp(argv[1], "--help") == 0) {
724 /* "busybox --help [<applet>]" */
727 /* convert to "<applet> --help" */
731 /* "busybox <applet> arg1 arg2 ..." */
734 /* We support "busybox /a/path/to/applet args..." too. Allows for
735 * "#!/bin/busybox"-style wrappers */
736 applet_name = bb_get_last_path_component_nostrip(argv[0]);
737 run_applet_and_exit(applet_name, argv);
739 /*bb_error_msg_and_die("applet not found"); - sucks in printf */
740 full_write2_str(applet_name);
741 full_write2_str(": applet not found\n");
745 void FAST_FUNC run_applet_no_and_exit(int applet_no, char **argv)
752 /* Reinit some shared global data */
753 xfunc_error_retval = EXIT_FAILURE;
755 applet_name = APPLET_NAME(applet_no);
756 if (argc == 2 && strcmp(argv[1], "--help") == 0) {
757 /* Special case. POSIX says "test --help"
758 * should be no different from e.g. "test --foo". */
759 //TODO: just compare applet_no with APPLET_NO_test
760 if (!ENABLE_TEST || strcmp(applet_name, "test") != 0)
763 if (ENABLE_FEATURE_SUID)
764 check_suid(applet_no);
765 exit(applet_main[applet_no](argc, argv));
768 void FAST_FUNC run_applet_and_exit(const char *name, char **argv)
770 int applet = find_applet_by_name(name);
772 run_applet_no_and_exit(applet, argv);
773 if (strncmp(name, "busybox", 7) == 0)
774 exit(busybox_main(argv));
777 #endif /* !defined(SINGLE_APPLET_MAIN) */
781 #if ENABLE_BUILD_LIBBUSYBOX
782 int lbb_main(char **argv)
784 int main(int argc UNUSED_PARAM, char **argv)
787 /* Tweak malloc for reduced memory consumption */
789 # define PAGE_SIZE (4*1024) /* guess */
791 #ifdef M_TRIM_THRESHOLD
792 /* M_TRIM_THRESHOLD is the maximum amount of freed top-most memory
793 * to keep before releasing to the OS
794 * Default is way too big: 256k
796 mallopt(M_TRIM_THRESHOLD, 2 * PAGE_SIZE);
798 #ifdef M_MMAP_THRESHOLD
799 /* M_MMAP_THRESHOLD is the request size threshold for using mmap()
800 * Default is too big: 256k
802 mallopt(M_MMAP_THRESHOLD, 8 * PAGE_SIZE - 256);
806 /* NOMMU re-exec trick sets high-order bit in first byte of name */
807 if (argv[0][0] & 0x80) {
813 #if defined(SINGLE_APPLET_MAIN)
814 /* Only one applet is selected in .config */
815 if (strncmp(argv[0], "busybox", 7) == 0) {
816 /* "busybox <applet> <params>" should still work as expected */
819 /* applet_names in this case is just "applet\0\0" */
820 lbb_prepare(applet_names IF_FEATURE_INDIVIDUAL(, argv));
821 return SINGLE_APPLET_MAIN(argc, argv);
823 lbb_prepare("busybox" IF_FEATURE_INDIVIDUAL(, argv));
825 applet_name = argv[0];
826 if (applet_name[0] == '-')
828 applet_name = bb_basename(applet_name);
830 parse_config_file(); /* ...maybe, if FEATURE_SUID_CONFIG */
832 run_applet_and_exit(applet_name, argv);
834 /*bb_error_msg_and_die("applet not found"); - sucks in printf */
835 full_write2_str(applet_name);
836 full_write2_str(": applet not found\n");