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 the GPL.
12 * Licensed under GPLv2 or later, see file License in this tarball for details.
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() */
46 #if ENABLE_SHOW_USAGE && !ENABLE_FEATURE_COMPRESS_USAGE
47 /* Define usage_messages[] */
48 static const char usage_messages[] ALIGN1 = ""
55 # define usage_messages 0
56 #endif /* SHOW_USAGE */
59 /* Include generated applet names, pointers to <applet>_main, etc */
60 #include "applet_tables.h"
61 /* ...and if applet_tables generator says we have only one applet... */
62 #ifdef SINGLE_APPLET_MAIN
63 #undef ENABLE_FEATURE_INDIVIDUAL
64 #define ENABLE_FEATURE_INDIVIDUAL 1
65 #undef IF_FEATURE_INDIVIDUAL
66 #define IF_FEATURE_INDIVIDUAL(...) __VA_ARGS__
70 #if ENABLE_FEATURE_COMPRESS_USAGE
72 #include "usage_compressed.h"
73 #include "unarchive.h"
75 static const char *unpack_usage_messages(void)
83 /* inbuf: */ (void *)packed_usage,
84 /* len: */ sizeof(packed_usage));
85 /* read_bunzip can longjmp to start_bunzip, and ultimately
86 * end up here with i != 0 on read data errors! Not trivial */
88 /* Cannot use xmalloc: will leak bd in NOFORK case! */
89 outbuf = malloc_or_warn(SIZEOF_usage_messages);
91 read_bunzip(bd, outbuf, SIZEOF_usage_messages);
96 #define dealloc_usage_messages(s) free(s)
100 #define unpack_usage_messages() usage_messages
101 #define dealloc_usage_messages(s) ((void)(s))
103 #endif /* FEATURE_COMPRESS_USAGE */
106 static void full_write2_str(const char *str)
108 xwrite_str(STDERR_FILENO, str);
111 void FAST_FUNC bb_show_usage(void)
113 if (ENABLE_SHOW_USAGE) {
114 #ifdef SINGLE_APPLET_STR
115 /* Imagine that this applet is "true". Dont suck in printf! */
117 const char *usage_string = p = unpack_usage_messages();
120 full_write2_str("No help available.\n\n");
122 full_write2_str("Usage: "SINGLE_APPLET_STR" ");
124 full_write2_str("\n\n");
126 if (ENABLE_FEATURE_CLEAN_UP)
127 dealloc_usage_messages((char*)usage_string);
130 const char *usage_string = p = unpack_usage_messages();
131 int ap = find_applet_by_name(applet_name);
133 if (ap < 0) /* never happens, paranoia */
136 while (*p++) continue;
139 full_write2_str(bb_banner);
140 full_write2_str(" multi-call binary.\n");
142 full_write2_str("\nNo help available.\n\n");
144 full_write2_str("\nUsage: ");
145 full_write2_str(applet_name);
146 full_write2_str(" ");
148 full_write2_str("\n\n");
150 if (ENABLE_FEATURE_CLEAN_UP)
151 dealloc_usage_messages((char*)usage_string);
158 /* NB: any char pointer will work as well, not necessarily applet_names */
159 static int applet_name_compare(const void *name, const void *v)
161 int i = (const char *)v - applet_names;
162 return strcmp(name, APPLET_NAME(i));
165 int FAST_FUNC find_applet_by_name(const char *name)
168 /* Do a binary search to find the applet entry given the name. */
170 p = bsearch(name, applet_names, ARRAY_SIZE(applet_main), 1, applet_name_compare);
173 return p - applet_names;
175 /* A version which does not pull in bsearch */
177 const char *p = applet_names;
178 while (i < NUM_APPLETS) {
179 if (strcmp(name, p) == 0)
189 void lbb_prepare(const char *applet
190 IF_FEATURE_INDIVIDUAL(, char **argv))
191 MAIN_EXTERNALLY_VISIBLE;
192 void lbb_prepare(const char *applet
193 IF_FEATURE_INDIVIDUAL(, char **argv))
196 (*(int **)&bb_errno) = __errno_location();
199 applet_name = applet;
201 /* Set locale for everybody except 'init' */
202 if (ENABLE_LOCALE_SUPPORT && getpid() != 1)
203 setlocale(LC_ALL, "");
205 #if ENABLE_FEATURE_INDIVIDUAL
206 /* Redundant for busybox (run_applet_and_exit covers that case)
207 * but needed for "individual applet" mode */
208 if (argv[1] && !argv[2] && strcmp(argv[1], "--help") == 0) {
209 /* Special case. POSIX says "test --help"
210 * should be no different from e.g. "test --foo". */
211 if (!ENABLE_TEST || strcmp(applet_name, "test") != 0)
217 /* The code below can well be in applets/applets.c, as it is used only
218 * for busybox binary, not "individual" binaries.
219 * However, keeping it here and linking it into libbusybox.so
220 * (together with remaining tiny applets/applets.o)
221 * makes it possible to avoid --whole-archive at link time.
222 * This makes (shared busybox) + libbusybox smaller.
223 * (--gc-sections would be even better....)
226 const char *applet_name;
232 /* If not built as a single-applet executable... */
233 #if !defined(SINGLE_APPLET_MAIN)
235 IF_FEATURE_SUID(static uid_t ruid;) /* real uid */
237 #if ENABLE_FEATURE_SUID_CONFIG
239 /* applets[] is const, so we have to define this "override" structure */
240 static struct BB_suid_config {
245 struct BB_suid_config *m_next;
248 static bool suid_cfg_readable;
250 /* check if u is member of group g */
251 static int ingroup(uid_t u, gid_t g)
253 struct group *grp = getgrgid(g);
258 for (mem = grp->gr_mem; *mem; mem++) {
259 struct passwd *pwd = getpwnam(*mem);
261 if (pwd && (pwd->pw_uid == u))
268 /* This should probably be a libbb routine. In that case,
269 * I'd probably rename it to something like bb_trimmed_slice.
271 static char *get_trimmed_slice(char *s, char *e)
273 /* First, consider the value at e to be nul and back up until we
274 * reach a non-space char. Set the char after that (possibly at
275 * the original e) to nul. */
283 /* Next, advance past all leading space and return a ptr to the
284 * first non-space char; possibly the terminating nul. */
285 return skip_whitespace(s);
288 /* Don't depend on the tools to combine strings. */
289 static const char config_file[] ALIGN1 = "/etc/busybox.conf";
291 /* We don't supply a value for the nul, so an index adjustment is
292 * necessary below. Also, we use unsigned short here to save some
293 * space even though these are really mode_t values. */
294 static const unsigned short mode_mask[] ALIGN2 = {
295 /* SST sst xxx --- */
296 S_ISUID, S_ISUID|S_IXUSR, S_IXUSR, 0, /* user */
297 S_ISGID, S_ISGID|S_IXGRP, S_IXGRP, 0, /* group */
298 0, S_IXOTH, S_IXOTH, 0 /* other */
301 #define parse_error(x) do { errmsg = x; goto pe_label; } while (0)
303 static void parse_config_file(void)
305 struct BB_suid_config *sct_head;
306 struct BB_suid_config *sct;
318 assert(!suid_config); /* Should be set to NULL by bss init. */
321 if (ruid == 0) /* run by root - don't need to even read config file */
324 if ((stat(config_file, &st) != 0) /* No config file? */
325 || !S_ISREG(st.st_mode) /* Not a regular file? */
326 || (st.st_uid != 0) /* Not owned by root? */
327 || (st.st_mode & (S_IWGRP | S_IWOTH)) /* Writable by non-root? */
328 || !(f = fopen_for_read(config_file)) /* Cannot open? */
333 suid_cfg_readable = 1;
340 if (!fgets(s, sizeof(buffer), f)) { /* Are we done? */
342 if (ferror(f)) { /* Make sure it wasn't a read error. */
343 parse_error("reading");
346 suid_config = sct_head; /* Success, so set the pointer. */
350 lc++; /* Got a (partial) line. */
352 /* If a line is too long for our buffer, we consider it an error.
353 * The following test does mistreat one corner case though.
354 * If the final line of the file does not end with a newline and
355 * yet exactly fills the buffer, it will be treated as too long
356 * even though there isn't really a problem. But it isn't really
357 * worth adding code to deal with such an unlikely situation, and
358 * we do err on the side of caution. Besides, the line would be
359 * too long if it did end with a newline. */
360 if (!strchr(s, '\n') && !feof(f)) {
361 parse_error("line too long");
364 /* Trim leading and trailing whitespace, ignoring comments, and
365 * check if the resulting string is empty. */
366 s = get_trimmed_slice(s, strchrnul(s, '#'));
371 /* Check for a section header. */
374 /* Unlike the old code, we ignore leading and trailing
375 * whitespace for the section name. We also require that
376 * there are no stray characters after the closing bracket. */
378 if (!e /* Missing right bracket? */
379 || e[1] /* Trailing characters? */
380 || !*(s = get_trimmed_slice(s+1, e)) /* Missing name? */
382 parse_error("section header");
384 /* Right now we only have one section so just check it.
385 * If more sections are added in the future, please don't
386 * resort to cascading ifs with multiple strcasecmp calls.
387 * That kind of bloated code is all too common. A loop
388 * and a string table would be a better choice unless the
389 * number of sections is very small. */
390 if (strcasecmp(s, "SUID") == 0) {
394 section = -1; /* Unknown section so set to skip. */
398 /* Process sections. */
400 if (section == 1) { /* SUID */
401 /* Since we trimmed leading and trailing space above, we're
402 * now looking for strings of the form
403 * <key>[::space::]*=[::space::]*<value>
404 * where both key and value could contain inner whitespace. */
406 /* First get the key (an applet name in our case). */
409 s = get_trimmed_slice(s, e);
411 if (!e || !*s) { /* Missing '=' or empty key. */
412 parse_error("keyword");
415 /* Ok, we have an applet name. Process the rhs if this
416 * applet is currently built in and ignore it otherwise.
417 * Note: this can hide config file bugs which only pop
418 * up when the busybox configuration is changed. */
419 applet_no = find_applet_by_name(s);
420 if (applet_no >= 0) {
421 /* Note: We currently don't check for duplicates!
422 * The last config line for each applet will be the
423 * one used since we insert at the head of the list.
424 * I suppose this could be considered a feature. */
425 sct = xmalloc(sizeof(struct BB_suid_config));
426 sct->m_applet = applet_no;
428 sct->m_next = sct_head;
431 /* Get the specified mode. */
433 e = skip_whitespace(e+1);
435 for (i = 0; i < 3; i++) {
436 /* There are 4 chars + 1 nul for each of user/group/other. */
437 static const char mode_chars[] ALIGN1 = "Ssx-\0" "Ssx-\0" "Ttx-";
440 q = strchrnul(mode_chars + 5*i, *e++);
444 /* Adjust by -i to account for nul. */
445 sct->m_mode |= mode_mask[(q - mode_chars) - i];
448 /* Now get the the user/group info. */
450 s = skip_whitespace(e);
452 /* Note: we require whitespace between the mode and the
453 * user/group info. */
454 if ((s == e) || !(e = strchr(s, '.'))) {
455 parse_error("<uid>.<gid>");
459 /* We can't use get_ug_id here since it would exit()
460 * if a uid or gid was not found. Oh well... */
461 sct->m_uid = bb_strtoul(s, NULL, 10);
463 struct passwd *pwd = getpwnam(s);
467 sct->m_uid = pwd->pw_uid;
470 sct->m_gid = bb_strtoul(e, NULL, 10);
475 parse_error("group");
477 sct->m_gid = grp->gr_gid;
483 /* Unknown sections are ignored. */
485 /* Encountering configuration lines prior to seeing a
486 * section header is treated as an error. This is how
487 * the old code worked, but it may not be desirable.
488 * We may want to simply ignore such lines in case they
489 * are used in some future version of busybox. */
491 parse_error("keyword outside section");
497 fprintf(stderr, "Parse error in %s, line %d: %s\n",
498 config_file, lc, errmsg);
501 /* Release any allocated memory before returning. */
503 sct = sct_head->m_next;
509 static inline void parse_config_file(void)
511 IF_FEATURE_SUID(ruid = getuid();)
513 #endif /* FEATURE_SUID_CONFIG */
516 #if ENABLE_FEATURE_SUID
517 static void check_suid(int applet_no)
519 gid_t rgid; /* real gid */
521 if (ruid == 0) /* set by parse_config_file() */
522 return; /* run by root - no need to check more */
525 #if ENABLE_FEATURE_SUID_CONFIG
526 if (suid_cfg_readable) {
528 struct BB_suid_config *sct;
531 for (sct = suid_config; sct; sct = sct->m_next) {
532 if (sct->m_applet == applet_no)
535 goto check_need_suid;
538 if (sct->m_uid == ruid)
541 else if ((sct->m_gid == rgid) || ingroup(ruid, sct->m_gid))
542 /* same group / in group */
545 if (!(m & S_IXOTH)) /* is x bit not set ? */
546 bb_error_msg_and_die("you have no permission to run this applet!");
548 /* _both_ sgid and group_exec have to be set for setegid */
549 if ((sct->m_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
551 /* else (no setegid) we will set egid = rgid */
553 /* We set effective AND saved ids. If saved-id is not set
554 * like we do below, seteiud(0) can still later succeed! */
555 if (setresgid(-1, rgid, rgid))
556 bb_perror_msg_and_die("setresgid");
558 /* do we have to set effective uid? */
560 if (sct->m_mode & S_ISUID)
562 /* else (no seteuid) we will set euid = ruid */
564 if (setresuid(-1, uid, uid))
565 bb_perror_msg_and_die("setresuid");
568 #if !ENABLE_FEATURE_SUID_CONFIG_QUIET
570 static bool onetime = 0;
574 fprintf(stderr, "Using fallback suid method\n");
580 if (APPLET_SUID(applet_no) == _BB_SUID_REQUIRE) {
581 /* Real uid is not 0. If euid isn't 0 too, suid bit
582 * is most probably not set on our executable */
584 bb_error_msg_and_die("must be suid to work properly");
585 } else if (APPLET_SUID(applet_no) == _BB_SUID_DROP) {
586 xsetgid(rgid); /* drop all privileges */
591 #define check_suid(x) ((void)0)
592 #endif /* FEATURE_SUID */
595 #if ENABLE_FEATURE_INSTALLER
596 /* create (sym)links for each applet */
597 static void install_links(const char *busybox, int use_symbolic_links,
598 char *custom_install_dir)
601 * this should be consistent w/ the enum,
602 * busybox.h::bb_install_loc_t, or else... */
603 static const char usr_bin [] ALIGN1 = "/usr/bin";
604 static const char usr_sbin[] ALIGN1 = "/usr/sbin";
605 static const char *const install_dir[] = {
606 &usr_bin [8], /* "", equivalent to "/" for concat_path_file() */
607 &usr_bin [4], /* "/bin" */
608 &usr_sbin[4], /* "/sbin" */
613 int (*lf)(const char *, const char *);
619 if (use_symbolic_links)
622 for (i = 0; i < ARRAY_SIZE(applet_main); i++) {
623 fpc = concat_path_file(
624 custom_install_dir ? custom_install_dir : install_dir[APPLET_INSTALL_LOC(i)],
626 // debug: bb_error_msg("%slinking %s to busybox",
627 // use_symbolic_links ? "sym" : "", fpc);
628 rc = lf(busybox, fpc);
629 if (rc != 0 && errno != EEXIST) {
630 bb_simple_perror_msg(fpc);
636 #define install_links(x,y,z) ((void)0)
637 #endif /* FEATURE_INSTALLER */
639 /* If we were called as "busybox..." */
640 static int busybox_main(char **argv)
643 /* Called without arguments */
646 unsigned output_width;
649 if (ENABLE_FEATURE_AUTOWIDTH) {
650 /* Obtain the terminal width */
651 get_terminal_width_height(0, &output_width, NULL);
655 full_write2_str(bb_banner); /* reuse const string */
656 full_write2_str(" multi-call binary.\n"); /* reuse */
658 "Copyright (C) 1998-2009 Erik Andersen, Rob Landley, Denys Vlasenko\n"
659 "and others. Licensed under GPLv2.\n"
660 "See source distribution for full notice.\n"
662 "Usage: busybox [function] [arguments]...\n"
663 " or: function [arguments]...\n"
665 "\tBusyBox is a multi-call binary that combines many common Unix\n"
666 "\tutilities into a single executable. Most people will create a\n"
667 "\tlink to busybox for each function they wish to use and BusyBox\n"
668 "\twill act like whatever it was invoked as.\n"
670 "Currently defined functions:\n");
673 /* prevent last comma to be in the very last pos */
676 int len2 = strlen(a) + 2;
677 if (col >= (int)output_width - len2) {
678 full_write2_str(",\n");
683 full_write2_str("\t");
685 full_write2_str(", ");
691 full_write2_str("\n\n");
695 if (ENABLE_FEATURE_INSTALLER && strcmp(argv[1], "--install") == 0) {
696 int use_symbolic_links;
698 busybox = xmalloc_readlink(bb_busybox_exec_path);
700 busybox = bb_busybox_exec_path;
701 /* busybox --install [-s] [DIR]: */
702 /* -s: make symlinks */
703 /* DIR: directory to install links to */
704 use_symbolic_links = (argv[2] && strcmp(argv[2], "-s") == 0 && argv++);
705 install_links(busybox, use_symbolic_links, argv[2]);
709 if (strcmp(argv[1], "--help") == 0) {
710 /* "busybox --help [<applet>]" */
713 /* convert to "<applet> --help" */
717 /* "busybox <applet> arg1 arg2 ..." */
720 /* We support "busybox /a/path/to/applet args..." too. Allows for
721 * "#!/bin/busybox"-style wrappers */
722 applet_name = bb_get_last_path_component_nostrip(argv[0]);
723 run_applet_and_exit(applet_name, argv);
725 /*bb_error_msg_and_die("applet not found"); - sucks in printf */
726 full_write2_str(applet_name);
727 full_write2_str(": applet not found\n");
731 void FAST_FUNC run_applet_no_and_exit(int applet_no, char **argv)
738 /* Reinit some shared global data */
739 xfunc_error_retval = EXIT_FAILURE;
741 applet_name = APPLET_NAME(applet_no);
742 if (argc == 2 && strcmp(argv[1], "--help") == 0) {
743 /* Special case. POSIX says "test --help"
744 * should be no different from e.g. "test --foo". */
745 //TODO: just compare applet_no with APPLET_NO_test
746 if (!ENABLE_TEST || strcmp(applet_name, "test") != 0)
749 if (ENABLE_FEATURE_SUID)
750 check_suid(applet_no);
751 exit(applet_main[applet_no](argc, argv));
754 void FAST_FUNC run_applet_and_exit(const char *name, char **argv)
756 int applet = find_applet_by_name(name);
758 run_applet_no_and_exit(applet, argv);
759 if (!strncmp(name, "busybox", 7))
760 exit(busybox_main(argv));
763 #endif /* !defined(SINGLE_APPLET_MAIN) */
767 #if ENABLE_BUILD_LIBBUSYBOX
768 int lbb_main(char **argv)
770 int main(int argc UNUSED_PARAM, char **argv)
773 /* Tweak malloc for reduced memory consumption */
775 # define PAGE_SIZE (4*1024) /* guess */
777 #ifdef M_TRIM_THRESHOLD
778 /* M_TRIM_THRESHOLD is the maximum amount of freed top-most memory
779 * to keep before releasing to the OS
780 * Default is way too big: 256k
782 mallopt(M_TRIM_THRESHOLD, 2 * PAGE_SIZE);
784 #ifdef M_MMAP_THRESHOLD
785 /* M_MMAP_THRESHOLD is the request size threshold for using mmap()
786 * Default is too big: 256k
788 mallopt(M_MMAP_THRESHOLD, 8 * PAGE_SIZE - 256);
791 #if defined(SINGLE_APPLET_MAIN)
792 /* Only one applet is selected by the user! */
793 /* applet_names in this case is just "applet\0\0" */
794 lbb_prepare(applet_names IF_FEATURE_INDIVIDUAL(, argv));
795 return SINGLE_APPLET_MAIN(argc, argv);
797 lbb_prepare("busybox" IF_FEATURE_INDIVIDUAL(, argv));
800 /* NOMMU re-exec trick sets high-order bit in first byte of name */
801 if (argv[0][0] & 0x80) {
806 applet_name = argv[0];
807 if (applet_name[0] == '-')
809 applet_name = bb_basename(applet_name);
811 parse_config_file(); /* ...maybe, if FEATURE_SUID_CONFIG */
813 run_applet_and_exit(applet_name, argv);
815 /*bb_error_msg_and_die("applet not found"); - sucks in printf */
816 full_write2_str(applet_name);
817 full_write2_str(": applet not found\n");