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 */
36 /* Define struct bb_applet applets[] */
39 #if ENABLE_FEATURE_SH_STANDALONE
40 /* -1 because last entry is NULL */
41 const unsigned short NUM_APPLETS = ARRAY_SIZE(applets) - 1;
45 #if ENABLE_FEATURE_COMPRESS_USAGE
47 #include "usage_compressed.h"
48 #include "unarchive.h"
50 static const char *unpack_usage_messages(void)
58 /* inbuf: */ packed_usage,
59 /* len: */ sizeof(packed_usage));
60 /* read_bunzip can longjmp to start_bunzip, and ultimately
61 * end up here with i != 0 on read data errors! Not trivial */
63 /* Cannot use xmalloc: will leak bd in NOFORK case! */
64 outbuf = malloc_or_warn(SIZEOF_usage_messages);
66 read_bunzip(bd, outbuf, SIZEOF_usage_messages);
71 #define dealloc_usage_messages(s) free(s)
75 #define unpack_usage_messages() usage_messages
76 #define dealloc_usage_messages(s) ((void)(s))
78 #endif /* FEATURE_COMPRESS_USAGE */
81 void bb_show_usage(void)
83 if (ENABLE_SHOW_USAGE) {
84 const char *format_string;
86 const char *usage_string = p = unpack_usage_messages();
87 const struct bb_applet *ap = find_applet_by_name(applet_name);
90 if (!ap) /* never happens, paranoia */
95 while (*p++) continue;
99 fprintf(stderr, "%s multi-call binary\n", bb_banner);
100 format_string = "\nUsage: %s %s\n\n";
102 format_string = "\nNo help available.\n\n";
103 fprintf(stderr, format_string, applet_name, p);
104 dealloc_usage_messages((char*)usage_string);
110 static int applet_name_compare(const void *name, const void *vapplet)
112 const struct bb_applet *applet = vapplet;
114 return strcmp(name, applet->name);
117 const struct bb_applet *find_applet_by_name(const char *name)
119 /* Do a binary search to find the applet entry given the name. */
120 return bsearch(name, applets, ARRAY_SIZE(applets)-1, sizeof(applets[0]),
121 applet_name_compare);
126 /* Make it reside in R/W memory: */
127 int *const bb_errno __attribute__ ((section (".data")));
130 void lbb_prepare(const char *applet, char **argv)
133 (*(int **)&bb_errno) = __errno_location();
135 applet_name = applet;
137 /* Set locale for everybody except 'init' */
138 if (ENABLE_LOCALE_SUPPORT && getpid() != 1)
139 setlocale(LC_ALL, "");
141 #if ENABLE_FEATURE_INDIVIDUAL
142 /* Redundant for busybox (run_applet_and_exit covers that case)
143 * but needed for "individual applet" mode */
144 if (argv[1] && strcmp(argv[1], "--help") == 0)
149 /* The code below can well be in applets/applets.c, as it is used only
150 * for busybox binary, not "individual" binaries.
151 * However, keeping it here and linking it into libbusybox.so
152 * (together with remaining tiny applets/applets.o)
153 * makes it possible to avoid --whole-archive at link time.
154 * This makes (shared busybox) + libbusybox smaller.
155 * (--gc-sections would be even better....)
158 const char *applet_name;
163 USE_FEATURE_SUID(static uid_t ruid;) /* real uid */
165 #if ENABLE_FEATURE_SUID_CONFIG
167 /* applets[] is const, so we have to define this "override" structure */
168 static struct BB_suid_config {
169 const struct bb_applet *m_applet;
173 struct BB_suid_config *m_next;
176 static bool suid_cfg_readable;
178 /* check if u is member of group g */
179 static int ingroup(uid_t u, gid_t g)
181 struct group *grp = getgrgid(g);
186 for (mem = grp->gr_mem; *mem; mem++) {
187 struct passwd *pwd = getpwnam(*mem);
189 if (pwd && (pwd->pw_uid == u))
196 /* This should probably be a libbb routine. In that case,
197 * I'd probably rename it to something like bb_trimmed_slice.
199 static char *get_trimmed_slice(char *s, char *e)
201 /* First, consider the value at e to be nul and back up until we
202 * reach a non-space char. Set the char after that (possibly at
203 * the original e) to nul. */
211 /* Next, advance past all leading space and return a ptr to the
212 * first non-space char; possibly the terminating nul. */
213 return skip_whitespace(s);
216 /* Don't depend on the tools to combine strings. */
217 static const char config_file[] ALIGN1 = "/etc/busybox.conf";
219 /* We don't supply a value for the nul, so an index adjustment is
220 * necessary below. Also, we use unsigned short here to save some
221 * space even though these are really mode_t values. */
222 static const unsigned short mode_mask[] ALIGN2 = {
223 /* SST sst xxx --- */
224 S_ISUID, S_ISUID|S_IXUSR, S_IXUSR, 0, /* user */
225 S_ISGID, S_ISGID|S_IXGRP, S_IXGRP, 0, /* group */
226 0, S_IXOTH, S_IXOTH, 0 /* other */
229 #define parse_error(x) do { errmsg = x; goto pe_label; } while (0)
231 static void parse_config_file(void)
233 struct BB_suid_config *sct_head;
234 struct BB_suid_config *sct;
235 const struct bb_applet *applet;
246 assert(!suid_config); /* Should be set to NULL by bss init. */
249 if (ruid == 0) /* run by root - don't need to even read config file */
252 if ((stat(config_file, &st) != 0) /* No config file? */
253 || !S_ISREG(st.st_mode) /* Not a regular file? */
254 || (st.st_uid != 0) /* Not owned by root? */
255 || (st.st_mode & (S_IWGRP | S_IWOTH)) /* Writable by non-root? */
256 || !(f = fopen(config_file, "r")) /* Cannot open? */
261 suid_cfg_readable = 1;
268 if (!fgets(s, sizeof(buffer), f)) { /* Are we done? */
269 if (ferror(f)) { /* Make sure it wasn't a read error. */
270 parse_error("reading");
273 suid_config = sct_head; /* Success, so set the pointer. */
277 lc++; /* Got a (partial) line. */
279 /* If a line is too long for our buffer, we consider it an error.
280 * The following test does mistreat one corner case though.
281 * If the final line of the file does not end with a newline and
282 * yet exactly fills the buffer, it will be treated as too long
283 * even though there isn't really a problem. But it isn't really
284 * worth adding code to deal with such an unlikely situation, and
285 * we do err on the side of caution. Besides, the line would be
286 * too long if it did end with a newline. */
287 if (!strchr(s, '\n') && !feof(f)) {
288 parse_error("line too long");
291 /* Trim leading and trailing whitespace, ignoring comments, and
292 * check if the resulting string is empty. */
293 s = get_trimmed_slice(s, strchrnul(s, '#'));
298 /* Check for a section header. */
301 /* Unlike the old code, we ignore leading and trailing
302 * whitespace for the section name. We also require that
303 * there are no stray characters after the closing bracket. */
305 if (!e /* Missing right bracket? */
306 || e[1] /* Trailing characters? */
307 || !*(s = get_trimmed_slice(s+1, e)) /* Missing name? */
309 parse_error("section header");
311 /* Right now we only have one section so just check it.
312 * If more sections are added in the future, please don't
313 * resort to cascading ifs with multiple strcasecmp calls.
314 * That kind of bloated code is all too common. A loop
315 * and a string table would be a better choice unless the
316 * number of sections is very small. */
317 if (strcasecmp(s, "SUID") == 0) {
321 section = -1; /* Unknown section so set to skip. */
325 /* Process sections. */
327 if (section == 1) { /* SUID */
328 /* Since we trimmed leading and trailing space above, we're
329 * now looking for strings of the form
330 * <key>[::space::]*=[::space::]*<value>
331 * where both key and value could contain inner whitespace. */
333 /* First get the key (an applet name in our case). */
336 s = get_trimmed_slice(s, e);
338 if (!e || !*s) { /* Missing '=' or empty key. */
339 parse_error("keyword");
342 /* Ok, we have an applet name. Process the rhs if this
343 * applet is currently built in and ignore it otherwise.
344 * Note: this can hide config file bugs which only pop
345 * up when the busybox configuration is changed. */
346 applet = find_applet_by_name(s);
348 /* Note: We currently don't check for duplicates!
349 * The last config line for each applet will be the
350 * one used since we insert at the head of the list.
351 * I suppose this could be considered a feature. */
352 sct = xmalloc(sizeof(struct BB_suid_config));
353 sct->m_applet = applet;
355 sct->m_next = sct_head;
358 /* Get the specified mode. */
360 e = skip_whitespace(e+1);
362 for (i = 0; i < 3; i++) {
363 /* There are 4 chars + 1 nul for each of user/group/other. */
364 static const char mode_chars[] ALIGN1 = "Ssx-\0" "Ssx-\0" "Ttx-";
367 q = strchrnul(mode_chars + 5*i, *e++);
371 /* Adjust by -i to account for nul. */
372 sct->m_mode |= mode_mask[(q - mode_chars) - i];
375 /* Now get the the user/group info. */
377 s = skip_whitespace(e);
379 /* Note: we require whitespace between the mode and the
380 * user/group info. */
381 if ((s == e) || !(e = strchr(s, '.'))) {
382 parse_error("<uid>.<gid>");
386 /* We can't use get_ug_id here since it would exit()
387 * if a uid or gid was not found. Oh well... */
388 sct->m_uid = bb_strtoul(s, NULL, 10);
390 struct passwd *pwd = getpwnam(s);
394 sct->m_uid = pwd->pw_uid;
397 sct->m_gid = bb_strtoul(e, NULL, 10);
402 parse_error("group");
404 sct->m_gid = grp->gr_gid;
410 /* Unknown sections are ignored. */
412 /* Encountering configuration lines prior to seeing a
413 * section header is treated as an error. This is how
414 * the old code worked, but it may not be desirable.
415 * We may want to simply ignore such lines in case they
416 * are used in some future version of busybox. */
418 parse_error("keyword outside section");
424 fprintf(stderr, "Parse error in %s, line %d: %s\n",
425 config_file, lc, errmsg);
428 /* Release any allocated memory before returning. */
430 sct = sct_head->m_next;
436 static inline void parse_config_file(void)
438 USE_FEATURE_SUID(ruid = getuid();)
440 #endif /* FEATURE_SUID_CONFIG */
443 #if ENABLE_FEATURE_SUID
444 static void check_suid(const struct bb_applet *applet)
446 gid_t rgid; /* real gid */
448 if (ruid == 0) /* set by parse_config_file() */
449 return; /* run by root - no need to check more */
452 #if ENABLE_FEATURE_SUID_CONFIG
453 if (suid_cfg_readable) {
455 struct BB_suid_config *sct;
458 for (sct = suid_config; sct; sct = sct->m_next) {
459 if (sct->m_applet == applet)
462 /* default: drop all privileges */
468 if (sct->m_uid == ruid)
471 else if ((sct->m_gid == rgid) || ingroup(ruid, sct->m_gid))
472 /* same group / in group */
475 if (!(m & S_IXOTH)) /* is x bit not set ? */
476 bb_error_msg_and_die("you have no permission to run this applet!");
478 /* _both_ sgid and group_exec have to be set for setegid */
479 if ((sct->m_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
481 /* else (no setegid) we will set egid = rgid */
483 /* We set effective AND saved ids. If saved-id is not set
484 * like we do below, seteiud(0) can still later succeed! */
485 if (setresgid(-1, rgid, rgid))
486 bb_perror_msg_and_die("setresgid");
488 /* do we have to set effective uid? */
490 if (sct->m_mode & S_ISUID)
492 /* else (no seteuid) we will set euid = ruid */
494 if (setresuid(-1, uid, uid))
495 bb_perror_msg_and_die("setresuid");
498 #if !ENABLE_FEATURE_SUID_CONFIG_QUIET
500 static bool onetime = 0;
504 fprintf(stderr, "Using fallback suid method\n");
510 if (applet->need_suid == _BB_SUID_ALWAYS) {
511 /* Real uid is not 0. If euid isn't 0 too, suid bit
512 * is most probably not set on our executable */
514 bb_error_msg_and_die("applet requires root privileges!");
515 } else if (applet->need_suid == _BB_SUID_NEVER) {
516 xsetgid(rgid); /* drop all privileges */
521 #define check_suid(x) ((void)0)
522 #endif /* FEATURE_SUID */
525 #if ENABLE_FEATURE_INSTALLER
526 /* create (sym)links for each applet */
527 static void install_links(const char *busybox, int use_symbolic_links)
530 * this should be consistent w/ the enum,
531 * busybox.h::bb_install_loc_t, or else... */
532 static const char usr_bin [] ALIGN1 = "/usr/bin";
533 static const char usr_sbin[] ALIGN1 = "/usr/sbin";
534 static const char *const install_dir[] = {
535 &usr_bin [8], /* "", equivalent to "/" for concat_path_file() */
536 &usr_bin [4], /* "/bin" */
537 &usr_sbin[4], /* "/sbin" */
542 int (*lf)(const char *, const char *) = link;
547 if (use_symbolic_links)
550 for (i = 0; applets[i].name != NULL; i++) {
551 fpc = concat_path_file(
552 install_dir[applets[i].install_loc],
554 rc = lf(busybox, fpc);
555 if (rc != 0 && errno != EEXIST) {
556 bb_simple_perror_msg(fpc);
562 #define install_links(x,y) ((void)0)
563 #endif /* FEATURE_INSTALLER */
565 /* If we were called as "busybox..." */
566 static int busybox_main(char **argv)
569 /* Called without arguments */
570 const struct bb_applet *a;
571 int col, output_width;
574 if (ENABLE_FEATURE_AUTOWIDTH) {
575 /* Obtain the terminal width */
576 get_terminal_width_height(0, &output_width, NULL);
578 /* leading tab and room to wrap */
579 output_width -= sizeof("start-stop-daemon, ") + 8;
581 printf("%s multi-call binary\n", bb_banner); /* reuse const string... */
582 printf("Copyright (C) 1998-2006 Erik Andersen, Rob Landley, and others.\n"
583 "Licensed under GPLv2. See source distribution for full notice.\n"
585 "Usage: busybox [function] [arguments]...\n"
586 " or: [function] [arguments]...\n"
588 "\tBusyBox is a multi-call binary that combines many common Unix\n"
589 "\tutilities into a single executable. Most people will create a\n"
590 "\tlink to busybox for each function they wish to use and BusyBox\n"
591 "\twill act like whatever it was invoked as!\n"
592 "\nCurrently defined functions:\n");
596 if (col > output_width) {
600 col += printf("%s%s", (col ? ", " : "\t"), a->name);
607 if (ENABLE_FEATURE_INSTALLER && strcmp(argv[1], "--install") == 0) {
609 busybox = xmalloc_readlink(bb_busybox_exec_path);
611 busybox = bb_busybox_exec_path;
612 /* -s makes symlinks */
613 install_links(busybox, argv[2] && strcmp(argv[2], "-s") == 0);
617 if (strcmp(argv[1], "--help") == 0) {
618 /* "busybox --help [<applet>]" */
621 /* convert to "<applet> --help" */
625 /* "busybox <applet> arg1 arg2 ..." */
628 /* We support "busybox /a/path/to/applet args..." too. Allows for
629 * "#!/bin/busybox"-style wrappers */
630 applet_name = bb_get_last_path_component_nostrip(argv[0]);
631 run_applet_and_exit(applet_name, argv);
632 bb_error_msg_and_die("applet not found");
635 void run_appletstruct_and_exit(const struct bb_applet *applet, char **argv)
642 /* Reinit some shared global data */
644 xfunc_error_retval = EXIT_FAILURE;
646 applet_name = applet->name;
647 if (argc == 2 && !strcmp(argv[1], "--help"))
649 if (ENABLE_FEATURE_SUID)
651 exit(applet->main(argc, argv));
654 void run_applet_and_exit(const char *name, char **argv)
656 const struct bb_applet *applet = find_applet_by_name(name);
658 run_appletstruct_and_exit(applet, argv);
659 if (!strncmp(name, "busybox", 7))
660 exit(busybox_main(argv));
664 #if ENABLE_BUILD_LIBBUSYBOX
665 int lbb_main(int argc, char **argv)
667 int main(int argc, char **argv)
670 lbb_prepare("busybox", argv);
673 /* NOMMU re-exec trick sets high-order bit in first byte of name */
674 if (argv[0][0] & 0x80) {
679 applet_name = argv[0];
680 if (applet_name[0] == '-')
682 applet_name = bb_basename(applet_name);
684 parse_config_file(); /* ...maybe, if FEATURE_SUID_CONFIG */
686 run_applet_and_exit(applet_name, argv);
687 bb_error_msg_and_die("applet not found");