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.
19 /* Declare <applet>_main() */
24 #if ENABLE_SHOW_USAGE && !ENABLE_FEATURE_COMPRESS_USAGE
25 /* Define usage_messages[] */
26 static const char usage_messages[] ALIGN1 = ""
33 #define usage_messages 0
34 #endif /* SHOW_USAGE */
37 /* Include generated applet names, pointers to <applet>_main, etc */
38 #include "applet_tables.h"
39 /* ...and if applet_tables generator says we have only one applet... */
40 #ifdef SINGLE_APPLET_MAIN
41 #undef ENABLE_FEATURE_INDIVIDUAL
42 #define ENABLE_FEATURE_INDIVIDUAL 1
43 #undef USE_FEATURE_INDIVIDUAL
44 #define USE_FEATURE_INDIVIDUAL(...) __VA_ARGS__
48 #if ENABLE_FEATURE_COMPRESS_USAGE
50 #include "usage_compressed.h"
51 #include "unarchive.h"
53 static const char *unpack_usage_messages(void)
61 /* inbuf: */ packed_usage,
62 /* len: */ sizeof(packed_usage));
63 /* read_bunzip can longjmp to start_bunzip, and ultimately
64 * end up here with i != 0 on read data errors! Not trivial */
66 /* Cannot use xmalloc: will leak bd in NOFORK case! */
67 outbuf = malloc_or_warn(SIZEOF_usage_messages);
69 read_bunzip(bd, outbuf, SIZEOF_usage_messages);
74 #define dealloc_usage_messages(s) free(s)
78 #define unpack_usage_messages() usage_messages
79 #define dealloc_usage_messages(s) ((void)(s))
81 #endif /* FEATURE_COMPRESS_USAGE */
84 void bb_show_usage(void)
86 if (ENABLE_SHOW_USAGE) {
87 #ifdef SINGLE_APPLET_STR
88 /* Imagine that this applet is "true". Dont suck in printf! */
90 const char *usage_string = p = unpack_usage_messages();
93 write(2, "\nNo help available.\n\n",
94 sizeof("\nNo help available.\n\n") - 1);
96 write(2, "\nUsage: "SINGLE_APPLET_STR" ",
97 sizeof("\nUsage: "SINGLE_APPLET_STR" ") - 1);
98 write(2, p, strlen(p));
101 dealloc_usage_messages((char*)usage_string);
103 // TODO: in this case, stdio is sucked in by busybox_main() anyway...
104 const char *format_string;
106 const char *usage_string = p = unpack_usage_messages();
107 int ap = find_applet_by_name(applet_name);
109 if (ap < 0) /* never happens, paranoia */
112 while (*p++) continue;
115 fprintf(stderr, "%s multi-call binary\n", bb_banner);
116 format_string = "\nUsage: %s %s\n\n";
118 format_string = "\nNo help available.\n\n";
119 fprintf(stderr, format_string, applet_name, p);
120 dealloc_usage_messages((char*)usage_string);
127 /* NB: any char pointer will work as well, not necessarily applet_names */
128 static int applet_name_compare(const void *name, const void *v)
130 int i = (const char *)v - applet_names;
131 return strcmp(name, APPLET_NAME(i));
133 int find_applet_by_name(const char *name)
135 /* Do a binary search to find the applet entry given the name. */
137 p = bsearch(name, applet_names, ARRAY_SIZE(applet_main), 1, applet_name_compare);
140 return p - applet_names;
145 /* Make it reside in R/W memory: */
146 int *const bb_errno __attribute__ ((section (".data")));
149 void lbb_prepare(const char *applet
150 USE_FEATURE_INDIVIDUAL(, char **argv))
151 MAIN_EXTERNALLY_VISIBLE;
152 void lbb_prepare(const char *applet
153 USE_FEATURE_INDIVIDUAL(, char **argv))
156 (*(int **)&bb_errno) = __errno_location();
159 applet_name = applet;
161 /* Set locale for everybody except 'init' */
162 if (ENABLE_LOCALE_SUPPORT && getpid() != 1)
163 setlocale(LC_ALL, "");
165 #if ENABLE_FEATURE_INDIVIDUAL
166 /* Redundant for busybox (run_applet_and_exit covers that case)
167 * but needed for "individual applet" mode */
168 if (argv[1] && strcmp(argv[1], "--help") == 0)
173 /* The code below can well be in applets/applets.c, as it is used only
174 * for busybox binary, not "individual" binaries.
175 * However, keeping it here and linking it into libbusybox.so
176 * (together with remaining tiny applets/applets.o)
177 * makes it possible to avoid --whole-archive at link time.
178 * This makes (shared busybox) + libbusybox smaller.
179 * (--gc-sections would be even better....)
182 const char *applet_name;
188 #if !ENABLE_FEATURE_INDIVIDUAL
190 USE_FEATURE_SUID(static uid_t ruid;) /* real uid */
192 #if ENABLE_FEATURE_SUID_CONFIG
194 /* applets[] is const, so we have to define this "override" structure */
195 static struct BB_suid_config {
200 struct BB_suid_config *m_next;
203 static bool suid_cfg_readable;
205 /* check if u is member of group g */
206 static int ingroup(uid_t u, gid_t g)
208 struct group *grp = getgrgid(g);
213 for (mem = grp->gr_mem; *mem; mem++) {
214 struct passwd *pwd = getpwnam(*mem);
216 if (pwd && (pwd->pw_uid == u))
223 /* This should probably be a libbb routine. In that case,
224 * I'd probably rename it to something like bb_trimmed_slice.
226 static char *get_trimmed_slice(char *s, char *e)
228 /* First, consider the value at e to be nul and back up until we
229 * reach a non-space char. Set the char after that (possibly at
230 * the original e) to nul. */
238 /* Next, advance past all leading space and return a ptr to the
239 * first non-space char; possibly the terminating nul. */
240 return skip_whitespace(s);
243 /* Don't depend on the tools to combine strings. */
244 static const char config_file[] ALIGN1 = "/etc/busybox.conf";
246 /* We don't supply a value for the nul, so an index adjustment is
247 * necessary below. Also, we use unsigned short here to save some
248 * space even though these are really mode_t values. */
249 static const unsigned short mode_mask[] ALIGN2 = {
250 /* SST sst xxx --- */
251 S_ISUID, S_ISUID|S_IXUSR, S_IXUSR, 0, /* user */
252 S_ISGID, S_ISGID|S_IXGRP, S_IXGRP, 0, /* group */
253 0, S_IXOTH, S_IXOTH, 0 /* other */
256 #define parse_error(x) do { errmsg = x; goto pe_label; } while (0)
258 static void parse_config_file(void)
260 struct BB_suid_config *sct_head;
261 struct BB_suid_config *sct;
273 assert(!suid_config); /* Should be set to NULL by bss init. */
276 if (ruid == 0) /* run by root - don't need to even read config file */
279 if ((stat(config_file, &st) != 0) /* No config file? */
280 || !S_ISREG(st.st_mode) /* Not a regular file? */
281 || (st.st_uid != 0) /* Not owned by root? */
282 || (st.st_mode & (S_IWGRP | S_IWOTH)) /* Writable by non-root? */
283 || !(f = fopen(config_file, "r")) /* Cannot open? */
288 suid_cfg_readable = 1;
295 if (!fgets(s, sizeof(buffer), f)) { /* Are we done? */
297 if (ferror(f)) { /* Make sure it wasn't a read error. */
298 parse_error("reading");
301 suid_config = sct_head; /* Success, so set the pointer. */
305 lc++; /* Got a (partial) line. */
307 /* If a line is too long for our buffer, we consider it an error.
308 * The following test does mistreat one corner case though.
309 * If the final line of the file does not end with a newline and
310 * yet exactly fills the buffer, it will be treated as too long
311 * even though there isn't really a problem. But it isn't really
312 * worth adding code to deal with such an unlikely situation, and
313 * we do err on the side of caution. Besides, the line would be
314 * too long if it did end with a newline. */
315 if (!strchr(s, '\n') && !feof(f)) {
316 parse_error("line too long");
319 /* Trim leading and trailing whitespace, ignoring comments, and
320 * check if the resulting string is empty. */
321 s = get_trimmed_slice(s, strchrnul(s, '#'));
326 /* Check for a section header. */
329 /* Unlike the old code, we ignore leading and trailing
330 * whitespace for the section name. We also require that
331 * there are no stray characters after the closing bracket. */
333 if (!e /* Missing right bracket? */
334 || e[1] /* Trailing characters? */
335 || !*(s = get_trimmed_slice(s+1, e)) /* Missing name? */
337 parse_error("section header");
339 /* Right now we only have one section so just check it.
340 * If more sections are added in the future, please don't
341 * resort to cascading ifs with multiple strcasecmp calls.
342 * That kind of bloated code is all too common. A loop
343 * and a string table would be a better choice unless the
344 * number of sections is very small. */
345 if (strcasecmp(s, "SUID") == 0) {
349 section = -1; /* Unknown section so set to skip. */
353 /* Process sections. */
355 if (section == 1) { /* SUID */
356 /* Since we trimmed leading and trailing space above, we're
357 * now looking for strings of the form
358 * <key>[::space::]*=[::space::]*<value>
359 * where both key and value could contain inner whitespace. */
361 /* First get the key (an applet name in our case). */
364 s = get_trimmed_slice(s, e);
366 if (!e || !*s) { /* Missing '=' or empty key. */
367 parse_error("keyword");
370 /* Ok, we have an applet name. Process the rhs if this
371 * applet is currently built in and ignore it otherwise.
372 * Note: this can hide config file bugs which only pop
373 * up when the busybox configuration is changed. */
374 applet_no = find_applet_by_name(s);
375 if (applet_no >= 0) {
376 /* Note: We currently don't check for duplicates!
377 * The last config line for each applet will be the
378 * one used since we insert at the head of the list.
379 * I suppose this could be considered a feature. */
380 sct = xmalloc(sizeof(struct BB_suid_config));
381 sct->m_applet = applet_no;
383 sct->m_next = sct_head;
386 /* Get the specified mode. */
388 e = skip_whitespace(e+1);
390 for (i = 0; i < 3; i++) {
391 /* There are 4 chars + 1 nul for each of user/group/other. */
392 static const char mode_chars[] ALIGN1 = "Ssx-\0" "Ssx-\0" "Ttx-";
395 q = strchrnul(mode_chars + 5*i, *e++);
399 /* Adjust by -i to account for nul. */
400 sct->m_mode |= mode_mask[(q - mode_chars) - i];
403 /* Now get the the user/group info. */
405 s = skip_whitespace(e);
407 /* Note: we require whitespace between the mode and the
408 * user/group info. */
409 if ((s == e) || !(e = strchr(s, '.'))) {
410 parse_error("<uid>.<gid>");
414 /* We can't use get_ug_id here since it would exit()
415 * if a uid or gid was not found. Oh well... */
416 sct->m_uid = bb_strtoul(s, NULL, 10);
418 struct passwd *pwd = getpwnam(s);
422 sct->m_uid = pwd->pw_uid;
425 sct->m_gid = bb_strtoul(e, NULL, 10);
430 parse_error("group");
432 sct->m_gid = grp->gr_gid;
438 /* Unknown sections are ignored. */
440 /* Encountering configuration lines prior to seeing a
441 * section header is treated as an error. This is how
442 * the old code worked, but it may not be desirable.
443 * We may want to simply ignore such lines in case they
444 * are used in some future version of busybox. */
446 parse_error("keyword outside section");
452 fprintf(stderr, "Parse error in %s, line %d: %s\n",
453 config_file, lc, errmsg);
456 /* Release any allocated memory before returning. */
458 sct = sct_head->m_next;
464 static inline void parse_config_file(void)
466 USE_FEATURE_SUID(ruid = getuid();)
468 #endif /* FEATURE_SUID_CONFIG */
471 #if ENABLE_FEATURE_SUID
472 static void check_suid(int applet_no)
474 gid_t rgid; /* real gid */
476 if (ruid == 0) /* set by parse_config_file() */
477 return; /* run by root - no need to check more */
480 #if ENABLE_FEATURE_SUID_CONFIG
481 if (suid_cfg_readable) {
483 struct BB_suid_config *sct;
486 for (sct = suid_config; sct; sct = sct->m_next) {
487 if (sct->m_applet == applet_no)
490 goto check_need_suid;
493 if (sct->m_uid == ruid)
496 else if ((sct->m_gid == rgid) || ingroup(ruid, sct->m_gid))
497 /* same group / in group */
500 if (!(m & S_IXOTH)) /* is x bit not set ? */
501 bb_error_msg_and_die("you have no permission to run this applet!");
503 /* _both_ sgid and group_exec have to be set for setegid */
504 if ((sct->m_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
506 /* else (no setegid) we will set egid = rgid */
508 /* We set effective AND saved ids. If saved-id is not set
509 * like we do below, seteiud(0) can still later succeed! */
510 if (setresgid(-1, rgid, rgid))
511 bb_perror_msg_and_die("setresgid");
513 /* do we have to set effective uid? */
515 if (sct->m_mode & S_ISUID)
517 /* else (no seteuid) we will set euid = ruid */
519 if (setresuid(-1, uid, uid))
520 bb_perror_msg_and_die("setresuid");
523 #if !ENABLE_FEATURE_SUID_CONFIG_QUIET
525 static bool onetime = 0;
529 fprintf(stderr, "Using fallback suid method\n");
535 if (APPLET_SUID(applet_no) == _BB_SUID_ALWAYS) {
536 /* Real uid is not 0. If euid isn't 0 too, suid bit
537 * is most probably not set on our executable */
539 bb_error_msg_and_die("must be suid to work properly");
540 } else if (APPLET_SUID(applet_no) == _BB_SUID_NEVER) {
541 xsetgid(rgid); /* drop all privileges */
546 #define check_suid(x) ((void)0)
547 #endif /* FEATURE_SUID */
550 #if ENABLE_FEATURE_INSTALLER
551 /* create (sym)links for each applet */
552 static void install_links(const char *busybox, int use_symbolic_links)
555 * this should be consistent w/ the enum,
556 * busybox.h::bb_install_loc_t, or else... */
557 static const char usr_bin [] ALIGN1 = "/usr/bin";
558 static const char usr_sbin[] ALIGN1 = "/usr/sbin";
559 static const char *const install_dir[] = {
560 &usr_bin [8], /* "", equivalent to "/" for concat_path_file() */
561 &usr_bin [4], /* "/bin" */
562 &usr_sbin[4], /* "/sbin" */
567 int (*lf)(const char *, const char *);
573 if (use_symbolic_links)
576 for (i = 0; i < ARRAY_SIZE(applet_main); i++) {
577 fpc = concat_path_file(
578 install_dir[APPLET_INSTALL_LOC(i)],
580 // debug: bb_error_msg("%slinking %s to busybox",
581 // use_symbolic_links ? "sym" : "", fpc);
582 rc = lf(busybox, fpc);
583 if (rc != 0 && errno != EEXIST) {
584 bb_simple_perror_msg(fpc);
590 #define install_links(x,y) ((void)0)
591 #endif /* FEATURE_INSTALLER */
593 /* If we were called as "busybox..." */
594 static int busybox_main(char **argv)
597 /* Called without arguments */
599 int col, output_width;
602 if (ENABLE_FEATURE_AUTOWIDTH) {
603 /* Obtain the terminal width */
604 get_terminal_width_height(0, &output_width, NULL);
606 /* leading tab and room to wrap */
607 output_width -= sizeof("start-stop-daemon, ") + 8;
609 printf("%s multi-call binary\n", bb_banner); /* reuse const string... */
610 printf("Copyright (C) 1998-2007 Erik Andersen, Rob Landley, Denys Vlasenko\n"
611 "and others. Licensed under GPLv2.\n"
612 "See source distribution for full notice.\n"
614 "Usage: busybox [function] [arguments]...\n"
615 " or: function [arguments]...\n"
617 "\tBusyBox is a multi-call binary that combines many common Unix\n"
618 "\tutilities into a single executable. Most people will create a\n"
619 "\tlink to busybox for each function they wish to use and BusyBox\n"
620 "\twill act like whatever it was invoked as!\n"
622 "Currently defined functions:\n");
626 if (col > output_width) {
630 col += printf("%s%s", (col ? ", " : "\t"), a);
637 if (ENABLE_FEATURE_INSTALLER && strcmp(argv[1], "--install") == 0) {
639 busybox = xmalloc_readlink(bb_busybox_exec_path);
641 busybox = bb_busybox_exec_path;
642 /* -s makes symlinks */
643 install_links(busybox, argv[2] && strcmp(argv[2], "-s") == 0);
647 if (strcmp(argv[1], "--help") == 0) {
648 /* "busybox --help [<applet>]" */
651 /* convert to "<applet> --help" */
655 /* "busybox <applet> arg1 arg2 ..." */
658 /* We support "busybox /a/path/to/applet args..." too. Allows for
659 * "#!/bin/busybox"-style wrappers */
660 applet_name = bb_get_last_path_component_nostrip(argv[0]);
661 run_applet_and_exit(applet_name, argv);
662 bb_error_msg_and_die("applet not found");
665 void run_applet_no_and_exit(int applet_no, char **argv)
672 /* Reinit some shared global data */
673 xfunc_error_retval = EXIT_FAILURE;
675 applet_name = APPLET_NAME(applet_no);
676 if (argc == 2 && !strcmp(argv[1], "--help"))
678 if (ENABLE_FEATURE_SUID)
679 check_suid(applet_no);
680 exit(applet_main[applet_no](argc, argv));
683 void run_applet_and_exit(const char *name, char **argv)
685 int applet = find_applet_by_name(name);
687 run_applet_no_and_exit(applet, argv);
688 if (!strncmp(name, "busybox", 7))
689 exit(busybox_main(argv));
692 #endif /* !ENABLE_FEATURE_INDIVIDUAL */
696 #if ENABLE_BUILD_LIBBUSYBOX
697 int lbb_main(char **argv)
699 int main(int argc ATTRIBUTE_UNUSED, char **argv)
702 #if ENABLE_FEATURE_INDIVIDUAL
703 /* Only one applet is selected by the user! */
704 lbb_prepare(SINGLE_APPLET_STR USE_FEATURE_INDIVIDUAL(, argv));
705 return SINGLE_APPLET_MAIN(argc, argv);
707 lbb_prepare("busybox" USE_FEATURE_INDIVIDUAL(, argv));
710 /* NOMMU re-exec trick sets high-order bit in first byte of name */
711 if (argv[0][0] & 0x80) {
716 applet_name = argv[0];
717 if (applet_name[0] == '-')
719 applet_name = bb_basename(applet_name);
721 parse_config_file(); /* ...maybe, if FEATURE_SUID_CONFIG */
723 run_applet_and_exit(applet_name, argv);
724 bb_error_msg_and_die("applet not found");