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.
18 /* Apparently uclibc defines __GLIBC__ (compat trick?). Oh well. */
19 #if ENABLE_STATIC && defined(__GLIBC__) && !defined(__UCLIBC__)
20 #warning Static linking against glibc produces buggy executables
21 #warning (glibc does not cope well with ld --gc-sections).
22 #warning See sources.redhat.com/bugzilla/show_bug.cgi?id=3400
23 #warning Note that glibc is unsuitable for static linking anyway.
24 #warning If you still want to do it, remove -Wl,--gc-sections
25 #warning from top-level Makefile and remove this warning.
26 #error Aborting compilation.
30 /* Declare <applet>_main() */
35 #if ENABLE_SHOW_USAGE && !ENABLE_FEATURE_COMPRESS_USAGE
36 /* Define usage_messages[] */
37 static const char usage_messages[] ALIGN1 = ""
44 #define usage_messages 0
45 #endif /* SHOW_USAGE */
47 /* Define struct bb_applet applets[] */
49 /* The -1 arises because of the {0,NULL,0,-1} entry. */
51 #if ENABLE_FEATURE_SH_STANDALONE
52 const unsigned short NUM_APPLETS = ARRAY_SIZE(applets);
54 const struct bb_applet *current_applet;
55 const char *applet_name ATTRIBUTE_EXTERNALLY_VISIBLE;
60 USE_FEATURE_SUID(static uid_t ruid;) /* real uid */
62 #if ENABLE_FEATURE_SUID_CONFIG
64 /* applets[] is const, so we have to define this "override" structure */
65 static struct BB_suid_config {
66 const struct bb_applet *m_applet;
70 struct BB_suid_config *m_next;
73 static bool suid_cfg_readable;
75 /* check if u is member of group g */
76 static int ingroup(uid_t u, gid_t g)
78 struct group *grp = getgrgid(g);
83 for (mem = grp->gr_mem; *mem; mem++) {
84 struct passwd *pwd = getpwnam(*mem);
86 if (pwd && (pwd->pw_uid == u))
93 /* This should probably be a libbb routine. In that case,
94 * I'd probably rename it to something like bb_trimmed_slice.
96 static char *get_trimmed_slice(char *s, char *e)
98 /* First, consider the value at e to be nul and back up until we
99 * reach a non-space char. Set the char after that (possibly at
100 * the original e) to nul. */
108 /* Next, advance past all leading space and return a ptr to the
109 * first non-space char; possibly the terminating nul. */
110 return skip_whitespace(s);
113 /* Don't depend on the tools to combine strings. */
114 static const char config_file[] ALIGN1 = "/etc/busybox.conf";
116 /* We don't supply a value for the nul, so an index adjustment is
117 * necessary below. Also, we use unsigned short here to save some
118 * space even though these are really mode_t values. */
119 static const unsigned short mode_mask[] ALIGN2 = {
120 /* SST sst xxx --- */
121 S_ISUID, S_ISUID|S_IXUSR, S_IXUSR, 0, /* user */
122 S_ISGID, S_ISGID|S_IXGRP, S_IXGRP, 0, /* group */
123 0, S_IXOTH, S_IXOTH, 0 /* other */
126 #define parse_error(x) do { errmsg = x; goto pe_label; } while (0)
128 static void parse_config_file(void)
130 struct BB_suid_config *sct_head;
131 struct BB_suid_config *sct;
132 const struct bb_applet *applet;
143 assert(!suid_config); /* Should be set to NULL by bss init. */
146 if (ruid == 0) /* run by root - don't need to even read config file */
149 if ((stat(config_file, &st) != 0) /* No config file? */
150 || !S_ISREG(st.st_mode) /* Not a regular file? */
151 || (st.st_uid != 0) /* Not owned by root? */
152 || (st.st_mode & (S_IWGRP | S_IWOTH)) /* Writable by non-root? */
153 || !(f = fopen(config_file, "r")) /* Cannot open? */
158 suid_cfg_readable = 1;
165 if (!fgets(s, sizeof(buffer), f)) { /* Are we done? */
166 if (ferror(f)) { /* Make sure it wasn't a read error. */
167 parse_error("reading");
170 suid_config = sct_head; /* Success, so set the pointer. */
174 lc++; /* Got a (partial) line. */
176 /* If a line is too long for our buffer, we consider it an error.
177 * The following test does mistreat one corner case though.
178 * If the final line of the file does not end with a newline and
179 * yet exactly fills the buffer, it will be treated as too long
180 * even though there isn't really a problem. But it isn't really
181 * worth adding code to deal with such an unlikely situation, and
182 * we do err on the side of caution. Besides, the line would be
183 * too long if it did end with a newline. */
184 if (!strchr(s, '\n') && !feof(f)) {
185 parse_error("line too long");
188 /* Trim leading and trailing whitespace, ignoring comments, and
189 * check if the resulting string is empty. */
190 s = get_trimmed_slice(s, strchrnul(s, '#'));
195 /* Check for a section header. */
198 /* Unlike the old code, we ignore leading and trailing
199 * whitespace for the section name. We also require that
200 * there are no stray characters after the closing bracket. */
202 if (!e /* Missing right bracket? */
203 || e[1] /* Trailing characters? */
204 || !*(s = get_trimmed_slice(s+1, e)) /* Missing name? */
206 parse_error("section header");
208 /* Right now we only have one section so just check it.
209 * If more sections are added in the future, please don't
210 * resort to cascading ifs with multiple strcasecmp calls.
211 * That kind of bloated code is all too common. A loop
212 * and a string table would be a better choice unless the
213 * number of sections is very small. */
214 if (strcasecmp(s, "SUID") == 0) {
218 section = -1; /* Unknown section so set to skip. */
222 /* Process sections. */
224 if (section == 1) { /* SUID */
225 /* Since we trimmed leading and trailing space above, we're
226 * now looking for strings of the form
227 * <key>[::space::]*=[::space::]*<value>
228 * where both key and value could contain inner whitespace. */
230 /* First get the key (an applet name in our case). */
233 s = get_trimmed_slice(s, e);
235 if (!e || !*s) { /* Missing '=' or empty key. */
236 parse_error("keyword");
239 /* Ok, we have an applet name. Process the rhs if this
240 * applet is currently built in and ignore it otherwise.
241 * Note: this can hide config file bugs which only pop
242 * up when the busybox configuration is changed. */
243 applet = find_applet_by_name(s);
245 /* Note: We currently don't check for duplicates!
246 * The last config line for each applet will be the
247 * one used since we insert at the head of the list.
248 * I suppose this could be considered a feature. */
249 sct = xmalloc(sizeof(struct BB_suid_config));
250 sct->m_applet = applet;
252 sct->m_next = sct_head;
255 /* Get the specified mode. */
257 e = skip_whitespace(e+1);
259 for (i = 0; i < 3; i++) {
260 /* There are 4 chars + 1 nul for each of user/group/other. */
261 static const char mode_chars[] ALIGN1 = "Ssx-\0" "Ssx-\0" "Ttx-";
264 q = strchrnul(mode_chars + 5*i, *e++);
268 /* Adjust by -i to account for nul. */
269 sct->m_mode |= mode_mask[(q - mode_chars) - i];
272 /* Now get the the user/group info. */
274 s = skip_whitespace(e);
276 /* Note: we require whitespace between the mode and the
277 * user/group info. */
278 if ((s == e) || !(e = strchr(s, '.'))) {
279 parse_error("<uid>.<gid>");
283 /* We can't use get_ug_id here since it would exit()
284 * if a uid or gid was not found. Oh well... */
285 sct->m_uid = bb_strtoul(s, NULL, 10);
287 struct passwd *pwd = getpwnam(s);
291 sct->m_uid = pwd->pw_uid;
294 sct->m_gid = bb_strtoul(e, NULL, 10);
299 parse_error("group");
301 sct->m_gid = grp->gr_gid;
307 /* Unknown sections are ignored. */
309 /* Encountering configuration lines prior to seeing a
310 * section header is treated as an error. This is how
311 * the old code worked, but it may not be desirable.
312 * We may want to simply ignore such lines in case they
313 * are used in some future version of busybox. */
315 parse_error("keyword outside section");
321 fprintf(stderr, "Parse error in %s, line %d: %s\n",
322 config_file, lc, errmsg);
325 /* Release any allocated memory before returning. */
327 sct = sct_head->m_next;
333 static inline void parse_config_file(void)
335 USE_FEATURE_SUID(ruid = getuid();)
337 #endif /* FEATURE_SUID_CONFIG */
340 #if ENABLE_FEATURE_SUID
341 static void check_suid(const struct bb_applet *applet)
343 gid_t rgid; /* real gid */
345 if (ruid == 0) /* set by parse_config_file() */
346 return; /* run by root - no need to check more */
349 #if ENABLE_FEATURE_SUID_CONFIG
350 if (suid_cfg_readable) {
352 struct BB_suid_config *sct;
355 for (sct = suid_config; sct; sct = sct->m_next) {
356 if (sct->m_applet == applet)
359 /* default: drop all privileges */
365 if (sct->m_uid == ruid)
368 else if ((sct->m_gid == rgid) || ingroup(ruid, sct->m_gid))
369 /* same group / in group */
372 if (!(m & S_IXOTH)) /* is x bit not set ? */
373 bb_error_msg_and_die("you have no permission to run this applet!");
375 /* _both_ sgid and group_exec have to be set for setegid */
376 if ((sct->m_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
378 /* else (no setegid) we will set egid = rgid */
380 /* We set effective AND saved ids. If saved-id is not set
381 * like we do below, seteiud(0) can still later succeed! */
382 if (setresgid(-1, rgid, rgid))
383 bb_perror_msg_and_die("setresgid");
385 /* do we have to set effective uid? */
387 if (sct->m_mode & S_ISUID)
389 /* else (no seteuid) we will set euid = ruid */
391 if (setresuid(-1, uid, uid))
392 bb_perror_msg_and_die("setresuid");
395 #if !ENABLE_FEATURE_SUID_CONFIG_QUIET
397 static bool onetime = 0;
401 fprintf(stderr, "Using fallback suid method\n");
407 if (applet->need_suid == _BB_SUID_ALWAYS) {
408 /* Real uid is not 0. If euid isn't 0 too, suid bit
409 * is most probably not set on our executable */
411 bb_error_msg_and_die("applet requires root privileges!");
412 } else if (applet->need_suid == _BB_SUID_NEVER) {
413 xsetgid(rgid); /* drop all privileges */
418 #define check_suid(x) ((void)0)
419 #endif /* FEATURE_SUID */
422 #if ENABLE_FEATURE_COMPRESS_USAGE
424 #include "usage_compressed.h"
425 #include "unarchive.h"
427 static const char *unpack_usage_messages(void)
433 i = start_bunzip(&bd,
435 /* inbuf: */ packed_usage,
436 /* len: */ sizeof(packed_usage));
437 /* read_bunzip can longjmp to start_bunzip, and ultimately
438 * end up here with i != 0 on read data errors! Not trivial */
440 /* Cannot use xmalloc: will leak bd in NOFORK case! */
441 outbuf = malloc_or_warn(SIZEOF_usage_messages);
443 read_bunzip(bd, outbuf, SIZEOF_usage_messages);
448 #define dealloc_usage_messages(s) free(s)
452 #define unpack_usage_messages() usage_messages
453 #define dealloc_usage_messages(s) ((void)(s))
455 #endif /* FEATURE_COMPRESS_USAGE */
458 void bb_show_usage(void)
460 if (ENABLE_SHOW_USAGE) {
461 const char *format_string;
463 const char *usage_string = p = unpack_usage_messages();
466 i = current_applet - applets;
468 while (*p++) continue;
472 fprintf(stderr, "%s multi-call binary\n", bb_banner);
473 format_string = "\nUsage: %s %s\n\n";
475 format_string = "\nNo help available.\n\n";
476 fprintf(stderr, format_string, applet_name, p);
477 dealloc_usage_messages((char*)usage_string);
483 static int applet_name_compare(const void *name, const void *vapplet)
485 const struct bb_applet *applet = vapplet;
487 return strcmp(name, applet->name);
490 const struct bb_applet *find_applet_by_name(const char *name)
492 /* Do a binary search to find the applet entry given the name. */
493 return bsearch(name, applets, ARRAY_SIZE(applets)-1, sizeof(applets[0]),
494 applet_name_compare);
498 #if ENABLE_FEATURE_INSTALLER
499 /* create (sym)links for each applet */
500 static void install_links(const char *busybox, int use_symbolic_links)
503 * this should be consistent w/ the enum,
504 * busybox.h::bb_install_loc_t, or else... */
505 static const char usr_bin [] ALIGN1 = "/usr/bin";
506 static const char usr_sbin[] ALIGN1 = "/usr/sbin";
507 static const char *const install_dir[] = {
508 &usr_bin [8], /* "", equivalent to "/" for concat_path_file() */
509 &usr_bin [4], /* "/bin" */
510 &usr_sbin[4], /* "/sbin" */
515 int (*lf)(const char *, const char *) = link;
520 if (use_symbolic_links)
523 for (i = 0; applets[i].name != NULL; i++) {
524 fpc = concat_path_file(
525 install_dir[applets[i].install_loc],
527 rc = lf(busybox, fpc);
528 if (rc != 0 && errno != EEXIST) {
529 bb_perror_msg("%s", fpc);
535 #define install_links(x,y) ((void)0)
536 #endif /* FEATURE_INSTALLER */
539 /* If we were called as "busybox..." */
540 static int busybox_main(char **argv)
543 /* Called without arguments */
544 const struct bb_applet *a;
545 int col, output_width;
548 if (ENABLE_FEATURE_AUTOWIDTH) {
549 /* Obtain the terminal width */
550 get_terminal_width_height(0, &output_width, NULL);
552 /* leading tab and room to wrap */
553 output_width -= sizeof("start-stop-daemon, ") + 8;
555 printf("%s multi-call binary\n", bb_banner); /* reuse const string... */
556 printf("Copyright (C) 1998-2006 Erik Andersen, Rob Landley, and others.\n"
557 "Licensed under GPLv2. See source distribution for full notice.\n"
559 "Usage: busybox [function] [arguments]...\n"
560 " or: [function] [arguments]...\n"
562 "\tBusyBox is a multi-call binary that combines many common Unix\n"
563 "\tutilities into a single executable. Most people will create a\n"
564 "\tlink to busybox for each function they wish to use and BusyBox\n"
565 "\twill act like whatever it was invoked as!\n"
566 "\nCurrently defined functions:\n");
570 if (col > output_width) {
574 col += printf("%s%s", (col ? ", " : "\t"), a->name);
581 if (ENABLE_FEATURE_INSTALLER && strcmp(argv[1], "--install") == 0) {
583 busybox = xmalloc_readlink(bb_busybox_exec_path);
585 busybox = bb_busybox_exec_path;
586 /* -s makes symlinks */
587 install_links(busybox, argv[2] && strcmp(argv[2], "-s") == 0);
591 if (strcmp(argv[1], "--help") == 0) {
592 /* "busybox --help [<applet>]" */
595 /* convert to "<applet> --help" */
599 /* "busybox <applet> arg1 arg2 ..." */
602 /* We support "busybox /a/path/to/applet args..." too. Allows for
603 * "#!/bin/busybox"-style wrappers */
604 applet_name = bb_get_last_path_component(argv[0]);
605 run_applet_and_exit(applet_name, argv);
606 bb_error_msg_and_die("applet not found");
609 void run_current_applet_and_exit(char **argv)
616 /* Reinit some shared global data */
618 xfunc_error_retval = EXIT_FAILURE;
620 applet_name = current_applet->name;
621 if (argc == 2 && !strcmp(argv[1], "--help"))
623 if (ENABLE_FEATURE_SUID)
624 check_suid(current_applet);
625 exit(current_applet->main(argc, argv));
628 void run_applet_and_exit(const char *name, char **argv)
630 current_applet = find_applet_by_name(name);
632 run_current_applet_and_exit(argv);
633 if (!strncmp(name, "busybox", 7))
634 exit(busybox_main(argv));
639 /* Make it reside in R/W memory: */
640 int *const bb_errno __attribute__ ((section (".data")));
643 int main(int argc, char **argv)
646 (*(int **)&bb_errno) = __errno_location();
650 /* NOMMU re-exec trick sets high-order bit in first byte of name */
651 if (argv[0][0] & 0x80) {
656 applet_name = argv[0];
657 if (applet_name[0] == '-')
659 applet_name = bb_basename(applet_name);
661 parse_config_file(); /* ...maybe, if FEATURE_SUID_CONFIG */
663 /* Set locale for everybody except 'init' */
664 if (ENABLE_LOCALE_SUPPORT && getpid() != 1)
665 setlocale(LC_ALL, "");
667 run_applet_and_exit(applet_name, argv);
668 bb_error_msg_and_die("applet not found");