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.
29 /* Declare <applet>_main() */
34 #if ENABLE_SHOW_USAGE && !ENABLE_FEATURE_COMPRESS_USAGE
35 /* Define usage_messages[] */
36 static const char usage_messages[] = ""
43 #define usage_messages 0
44 #endif /* SHOW_USAGE */
46 /* Define struct bb_applet applets[] */
48 /* The -1 arises because of the {0,NULL,0,-1} entry. */
49 const unsigned short NUM_APPLETS = sizeof(applets) / sizeof(applets[0]) - 1;
51 const struct bb_applet *current_applet;
52 const char *applet_name ATTRIBUTE_EXTERNALLY_VISIBLE;
57 USE_FEATURE_SUID(static uid_t ruid;) /* real uid */
59 #if ENABLE_FEATURE_SUID_CONFIG
61 /* applets[] is const, so we have to define this "override" structure */
62 static struct BB_suid_config {
63 const struct bb_applet *m_applet;
67 struct BB_suid_config *m_next;
70 static bool suid_cfg_readable;
72 /* check if u is member of group g */
73 static int ingroup(uid_t u, gid_t g)
75 struct group *grp = getgrgid(g);
80 for (mem = grp->gr_mem; *mem; mem++) {
81 struct passwd *pwd = getpwnam(*mem);
83 if (pwd && (pwd->pw_uid == u))
90 /* This should probably be a libbb routine. In that case,
91 * I'd probably rename it to something like bb_trimmed_slice.
93 static char *get_trimmed_slice(char *s, char *e)
95 /* First, consider the value at e to be nul and back up until we
96 * reach a non-space char. Set the char after that (possibly at
97 * the original e) to nul. */
105 /* Next, advance past all leading space and return a ptr to the
106 * first non-space char; possibly the terminating nul. */
107 return skip_whitespace(s);
110 /* Don't depend on the tools to combine strings. */
111 static const char config_file[] = "/etc/busybox.conf";
113 /* We don't supply a value for the nul, so an index adjustment is
114 * necessary below. Also, we use unsigned short here to save some
115 * space even though these are really mode_t values. */
116 static const unsigned short mode_mask[] = {
117 /* SST sst xxx --- */
118 S_ISUID, S_ISUID|S_IXUSR, S_IXUSR, 0, /* user */
119 S_ISGID, S_ISGID|S_IXGRP, S_IXGRP, 0, /* group */
120 0, S_IXOTH, S_IXOTH, 0 /* other */
123 #define parse_error(x) do { errmsg = x; goto pe_label; } while (0)
125 static void parse_config_file(void)
127 struct BB_suid_config *sct_head;
128 struct BB_suid_config *sct;
129 const struct bb_applet *applet;
140 assert(!suid_config); /* Should be set to NULL by bss init. */
143 if (ruid == 0) /* run by root - don't need to even read config file */
146 if ((stat(config_file, &st) != 0) /* No config file? */
147 || !S_ISREG(st.st_mode) /* Not a regular file? */
148 || (st.st_uid != 0) /* Not owned by root? */
149 || (st.st_mode & (S_IWGRP | S_IWOTH)) /* Writable by non-root? */
150 || !(f = fopen(config_file, "r")) /* Cannot open? */
155 suid_cfg_readable = 1;
162 if (!fgets(s, sizeof(buffer), f)) { /* Are we done? */
163 if (ferror(f)) { /* Make sure it wasn't a read error. */
164 parse_error("reading");
167 suid_config = sct_head; /* Success, so set the pointer. */
171 lc++; /* Got a (partial) line. */
173 /* If a line is too long for our buffer, we consider it an error.
174 * The following test does mistreat one corner case though.
175 * If the final line of the file does not end with a newline and
176 * yet exactly fills the buffer, it will be treated as too long
177 * even though there isn't really a problem. But it isn't really
178 * worth adding code to deal with such an unlikely situation, and
179 * we do err on the side of caution. Besides, the line would be
180 * too long if it did end with a newline. */
181 if (!strchr(s, '\n') && !feof(f)) {
182 parse_error("line too long");
185 /* Trim leading and trailing whitespace, ignoring comments, and
186 * check if the resulting string is empty. */
187 s = get_trimmed_slice(s, strchrnul(s, '#'));
192 /* Check for a section header. */
195 /* Unlike the old code, we ignore leading and trailing
196 * whitespace for the section name. We also require that
197 * there are no stray characters after the closing bracket. */
199 if (!e /* Missing right bracket? */
200 || e[1] /* Trailing characters? */
201 || !*(s = get_trimmed_slice(s+1, e)) /* Missing name? */
203 parse_error("section header");
205 /* Right now we only have one section so just check it.
206 * If more sections are added in the future, please don't
207 * resort to cascading ifs with multiple strcasecmp calls.
208 * That kind of bloated code is all too common. A loop
209 * and a string table would be a better choice unless the
210 * number of sections is very small. */
211 if (strcasecmp(s, "SUID") == 0) {
215 section = -1; /* Unknown section so set to skip. */
219 /* Process sections. */
221 if (section == 1) { /* SUID */
222 /* Since we trimmed leading and trailing space above, we're
223 * now looking for strings of the form
224 * <key>[::space::]*=[::space::]*<value>
225 * where both key and value could contain inner whitespace. */
227 /* First get the key (an applet name in our case). */
230 s = get_trimmed_slice(s, e);
232 if (!e || !*s) { /* Missing '=' or empty key. */
233 parse_error("keyword");
236 /* Ok, we have an applet name. Process the rhs if this
237 * applet is currently built in and ignore it otherwise.
238 * Note: this can hide config file bugs which only pop
239 * up when the busybox configuration is changed. */
240 applet = find_applet_by_name(s);
242 /* Note: We currently don't check for duplicates!
243 * The last config line for each applet will be the
244 * one used since we insert at the head of the list.
245 * I suppose this could be considered a feature. */
246 sct = xmalloc(sizeof(struct BB_suid_config));
247 sct->m_applet = applet;
249 sct->m_next = sct_head;
252 /* Get the specified mode. */
254 e = skip_whitespace(e+1);
256 for (i = 0; i < 3; i++) {
257 /* There are 4 chars + 1 nul for each of user/group/other. */
258 static const char mode_chars[] = "Ssx-\0" "Ssx-\0" "Ttx-";
261 q = strchrnul(mode_chars + 5*i, *e++);
265 /* Adjust by -i to account for nul. */
266 sct->m_mode |= mode_mask[(q - mode_chars) - i];
269 /* Now get the the user/group info. */
271 s = skip_whitespace(e);
273 /* Note: we require whitespace between the mode and the
274 * user/group info. */
275 if ((s == e) || !(e = strchr(s, '.'))) {
276 parse_error("<uid>.<gid>");
280 /* We can't use get_ug_id here since it would exit()
281 * if a uid or gid was not found. Oh well... */
282 sct->m_uid = bb_strtoul(s, NULL, 10);
284 struct passwd *pwd = getpwnam(s);
288 sct->m_uid = pwd->pw_uid;
291 sct->m_gid = bb_strtoul(e, NULL, 10);
296 parse_error("group");
298 sct->m_gid = grp->gr_gid;
304 /* Unknown sections are ignored. */
306 /* Encountering configuration lines prior to seeing a
307 * section header is treated as an error. This is how
308 * the old code worked, but it may not be desirable.
309 * We may want to simply ignore such lines in case they
310 * are used in some future version of busybox. */
312 parse_error("keyword outside section");
318 fprintf(stderr, "Parse error in %s, line %d: %s\n",
319 config_file, lc, errmsg);
322 /* Release any allocated memory before returning. */
324 sct = sct_head->m_next;
330 static inline void parse_config_file(void)
332 USE_FEATURE_SUID(ruid = getuid();)
334 #endif /* FEATURE_SUID_CONFIG */
337 #if ENABLE_FEATURE_SUID
338 static void check_suid(const struct bb_applet *applet)
340 gid_t rgid; /* real gid */
342 if (ruid == 0) /* set by parse_config_file() */
343 return; /* run by root - no need to check more */
346 #if ENABLE_FEATURE_SUID_CONFIG
347 if (suid_cfg_readable) {
349 struct BB_suid_config *sct;
352 for (sct = suid_config; sct; sct = sct->m_next) {
353 if (sct->m_applet == applet)
356 /* default: drop all privileges */
362 if (sct->m_uid == ruid)
365 else if ((sct->m_gid == rgid) || ingroup(ruid, sct->m_gid))
366 /* same group / in group */
369 if (!(m & S_IXOTH)) /* is x bit not set ? */
370 bb_error_msg_and_die("you have no permission to run this applet!");
372 /* _both_ sgid and group_exec have to be set for setegid */
373 if ((sct->m_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
375 /* else (no setegid) we will set egid = rgid */
377 /* We set effective AND saved ids. If saved-id is not set
378 * like we do below, seteiud(0) can still later succeed! */
379 if (setresgid(-1, rgid, rgid))
380 bb_perror_msg_and_die("setresgid");
382 /* do we have to set effective uid? */
384 if (sct->m_mode & S_ISUID)
386 /* else (no seteuid) we will set euid = ruid */
388 if (setresuid(-1, uid, uid))
389 bb_perror_msg_and_die("setresuid");
392 #if !ENABLE_FEATURE_SUID_CONFIG_QUIET
394 static bool onetime = 0;
398 fprintf(stderr, "Using fallback suid method\n");
404 if (applet->need_suid == _BB_SUID_ALWAYS) {
405 /* Real uid is not 0. If euid isn't 0 too, suid bit
406 * is most probably not set on our executable */
408 bb_error_msg_and_die("applet requires root privileges!");
409 } else if (applet->need_suid == _BB_SUID_NEVER) {
410 xsetgid(rgid); /* drop all privileges */
415 #define check_suid(x) ((void)0)
416 #endif /* FEATURE_SUID */
419 #if ENABLE_FEATURE_COMPRESS_USAGE
421 #include "usage_compressed.h"
422 #include "unarchive.h"
424 static const char *unpack_usage_messages(void)
430 i = start_bunzip(&bd,
432 /* inbuf: */ packed_usage,
433 /* len: */ sizeof(packed_usage));
434 /* read_bunzip can longjmp to start_bunzip, and ultimately
435 * end up here with i != 0 on read data errors! Not trivial */
437 /* Cannot use xmalloc: will leak bd in NOFORK case! */
438 outbuf = malloc_or_warn(SIZEOF_usage_messages);
440 read_bunzip(bd, outbuf, SIZEOF_usage_messages);
445 #define dealloc_usage_messages(s) free(s)
449 #define unpack_usage_messages() usage_messages
450 #define dealloc_usage_messages(s) ((void)(s))
452 #endif /* FEATURE_COMPRESS_USAGE */
455 void bb_show_usage(void)
457 if (ENABLE_SHOW_USAGE) {
458 const char *format_string;
460 const char *usage_string = p = unpack_usage_messages();
463 i = current_applet - applets;
465 while (*p++) continue;
469 format_string = "%s\n\nUsage: %s %s\n\n";
471 format_string = "%s\n\nNo help available.\n\n";
472 fprintf(stderr, format_string, bb_msg_full_version,
474 dealloc_usage_messages((char*)usage_string);
480 static int applet_name_compare(const void *name, const void *vapplet)
482 const struct bb_applet *applet = vapplet;
484 return strcmp(name, applet->name);
487 const struct bb_applet *find_applet_by_name(const char *name)
489 /* Do a binary search to find the applet entry given the name. */
490 return bsearch(name, applets, NUM_APPLETS, sizeof(applets[0]),
491 applet_name_compare);
495 #if ENABLE_FEATURE_INSTALLER
496 /* create (sym)links for each applet */
497 static void install_links(const char *busybox, int use_symbolic_links)
500 * this should be consistent w/ the enum,
501 * busybox.h::bb_install_loc_t, or else... */
502 static const char usr_bin [] = "/usr/bin";
503 static const char usr_sbin[] = "/usr/sbin";
504 static const char *const install_dir[] = {
505 &usr_bin [8], /* "", equivalent to "/" for concat_path_file() */
506 &usr_bin [4], /* "/bin" */
507 &usr_sbin[4], /* "/sbin" */
512 int (*lf)(const char *, const char *) = link;
517 if (use_symbolic_links)
520 for (i = 0; applets[i].name != NULL; i++) {
521 fpc = concat_path_file(
522 install_dir[applets[i].install_loc],
524 rc = lf(busybox, fpc);
525 if (rc != 0 && errno != EEXIST) {
526 bb_perror_msg("%s", fpc);
532 #define install_links(x,y) ((void)0)
533 #endif /* FEATURE_INSTALLER */
536 /* If we were called as "busybox..." */
537 static int busybox_main(char **argv)
540 /* Called without arguments */
541 const struct bb_applet *a;
542 int col, output_width;
545 if (ENABLE_FEATURE_AUTOWIDTH) {
546 /* Obtain the terminal width. */
547 get_terminal_width_height(0, &output_width, NULL);
549 /* leading tab and room to wrap */
550 output_width -= sizeof("start-stop-daemon, ") + 8;
553 "Copyright (C) 1998-2006 Erik Andersen, Rob Landley, and others.\n"
554 "Licensed under GPLv2. See source distribution for full notice.\n"
556 "Usage: busybox [function] [arguments]...\n"
557 " or: [function] [arguments]...\n"
559 "\tBusyBox is a multi-call binary that combines many common Unix\n"
560 "\tutilities into a single executable. Most people will create a\n"
561 "\tlink to busybox for each function they wish to use and BusyBox\n"
562 "\twill act like whatever it was invoked as!\n"
563 "\nCurrently defined functions:\n", bb_msg_full_version);
567 if (col > output_width) {
571 col += printf("%s%s", (col ? ", " : "\t"), a->name);
578 if (ENABLE_FEATURE_INSTALLER && strcmp(argv[1], "--install") == 0) {
579 int use_symbolic_links = 0;
582 /* to use symlinks, or not to use symlinks... */
584 if (strcmp(argv[2], "-s") == 0)
585 use_symbolic_links = 1;
588 busybox = xmalloc_readlink_or_warn("/proc/self/exe");
591 install_links(busybox, use_symbolic_links);
592 if (ENABLE_FEATURE_CLEAN_UP)
597 if (strcmp(argv[1], "--help") == 0) {
598 /* "busybox --help [<applet>]" */
601 /* convert to "<applet> --help" */
605 /* "busybox <applet> arg1 arg2 ..." */
608 /* we want "<argv[0]>: applet not found", not "busybox: ..." */
609 applet_name = argv[0];
610 run_applet_and_exit(argv[0], argv);
611 bb_error_msg_and_die("applet not found");
614 void run_current_applet_and_exit(char **argv)
621 /* Reinit some shared global data */
623 xfunc_error_retval = EXIT_FAILURE;
625 applet_name = current_applet->name;
626 if (argc == 2 && !strcmp(argv[1], "--help"))
628 if (ENABLE_FEATURE_SUID)
629 check_suid(current_applet);
630 exit(current_applet->main(argc, argv));
633 void run_applet_and_exit(const char *name, char **argv)
635 current_applet = find_applet_by_name(name);
637 run_current_applet_and_exit(argv);
638 if (!strncmp(name, "busybox", 7))
639 exit(busybox_main(argv));
643 int main(int argc, char **argv)
648 /* NOMMU re-exec trick sets high-order bit in first byte of name */
649 if (argv[0][0] & 0x80) {
654 applet_name = argv[0];
655 if (applet_name[0] == '-')
657 s = strrchr(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");