Remove requirement that include/applets.h must be sorted
[oweals/busybox.git] / libbb / appletlib.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Utility routines.
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.
8  *
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.
11  *
12  * Licensed under GPLv2 or later, see file License in this tarball for details.
13  */
14
15 /* We are trying to not use printf, this benefits the case when selected
16  * applets are really simple. Example:
17  *
18  * $ ./busybox
19  * ...
20  * Currently defined functions:
21  *         basename, false, true
22  *
23  * $ size busybox
24  *    text    data     bss     dec     hex filename
25  *    4473      52      72    4597    11f5 busybox
26  *
27  * FEATURE_INSTALLER or FEATURE_SUID will still link printf routines in. :(
28  */
29 #include "busybox.h"
30 #include <assert.h>
31 #include <malloc.h>
32 /* Try to pull in PAGE_SIZE */
33 #ifdef __linux__
34 # include <sys/user.h>
35 #endif
36 #ifdef __GNU__ /* Hurd */
37 # include <mach/vm_param.h>
38 #endif
39
40
41 /* Declare <applet>_main() */
42 #define PROTOTYPES
43 #include "applets.h"
44 #undef PROTOTYPES
45
46
47 /* Include generated applet names, pointers to <applet>_main, etc */
48 #include "applet_tables.h"
49 /* ...and if applet_tables generator says we have only one applet... */
50 #ifdef SINGLE_APPLET_MAIN
51 # undef ENABLE_FEATURE_INDIVIDUAL
52 # define ENABLE_FEATURE_INDIVIDUAL 1
53 # undef IF_FEATURE_INDIVIDUAL
54 # define IF_FEATURE_INDIVIDUAL(...) __VA_ARGS__
55 #endif
56
57
58 #include "usage_compressed.h"
59
60 #if ENABLE_SHOW_USAGE && !ENABLE_FEATURE_COMPRESS_USAGE
61 static const char usage_messages[] ALIGN1 = UNPACKED_USAGE;
62 #else
63 # define usage_messages 0
64 #endif /* SHOW_USAGE */
65
66 #if ENABLE_FEATURE_COMPRESS_USAGE
67
68 static const char packed_usage[] = { PACKED_USAGE };
69 # include "unarchive.h"
70 static const char *unpack_usage_messages(void)
71 {
72         char *outbuf = NULL;
73         bunzip_data *bd;
74         int i;
75
76         i = start_bunzip(&bd,
77                         /* src_fd: */ -1,
78                         /* inbuf:  */ (void *)packed_usage,
79                         /* len:    */ sizeof(packed_usage));
80         /* read_bunzip can longjmp to start_bunzip, and ultimately
81          * end up here with i != 0 on read data errors! Not trivial */
82         if (!i) {
83                 /* Cannot use xmalloc: will leak bd in NOFORK case! */
84                 outbuf = malloc_or_warn(sizeof(UNPACKED_USAGE));
85                 if (outbuf)
86                         read_bunzip(bd, outbuf, sizeof(UNPACKED_USAGE));
87         }
88         dealloc_bunzip(bd);
89         return outbuf;
90 }
91 # define dealloc_usage_messages(s) free(s)
92
93 #else
94
95 # define unpack_usage_messages() usage_messages
96 # define dealloc_usage_messages(s) ((void)(s))
97
98 #endif /* FEATURE_COMPRESS_USAGE */
99
100
101 static void full_write2_str(const char *str)
102 {
103         // This uses stdio:
104         //xwrite_str(STDERR_FILENO, str);
105         write(STDERR_FILENO, str, strlen(str));
106 }
107
108 void FAST_FUNC bb_show_usage(void)
109 {
110         if (ENABLE_SHOW_USAGE) {
111 #ifdef SINGLE_APPLET_STR
112                 /* Imagine that this applet is "true". Dont suck in printf! */
113                 const char *p;
114                 const char *usage_string = p = unpack_usage_messages();
115
116                 if (*p == '\b') {
117                         full_write2_str("No help available.\n\n");
118                 } else {
119                         full_write2_str("Usage: "SINGLE_APPLET_STR" ");
120                         full_write2_str(p);
121                         full_write2_str("\n\n");
122                 }
123                 if (ENABLE_FEATURE_CLEAN_UP)
124                         dealloc_usage_messages((char*)usage_string);
125 #else
126                 const char *p;
127                 const char *usage_string = p = unpack_usage_messages();
128                 int ap = find_applet_by_name(applet_name);
129
130                 if (ap < 0) /* never happens, paranoia */
131                         xfunc_die();
132                 while (ap) {
133                         while (*p++) continue;
134                         ap--;
135                 }
136                 full_write2_str(bb_banner);
137                 full_write2_str(" multi-call binary.\n");
138                 if (*p == '\b')
139                         full_write2_str("\nNo help available.\n\n");
140                 else {
141                         full_write2_str("\nUsage: ");
142                         full_write2_str(applet_name);
143                         full_write2_str(" ");
144                         full_write2_str(p);
145                         full_write2_str("\n\n");
146                 }
147                 if (ENABLE_FEATURE_CLEAN_UP)
148                         dealloc_usage_messages((char*)usage_string);
149 #endif
150         }
151         xfunc_die();
152 }
153
154 #if NUM_APPLETS > 8
155 /* NB: any char pointer will work as well, not necessarily applet_names */
156 static int applet_name_compare(const void *name, const void *v)
157 {
158         int i = (const char *)v - applet_names;
159         return strcmp(name, APPLET_NAME(i));
160 }
161 #endif
162 int FAST_FUNC find_applet_by_name(const char *name)
163 {
164 #if NUM_APPLETS > 8
165         /* Do a binary search to find the applet entry given the name. */
166         const char *p;
167         p = bsearch(name, applet_names, ARRAY_SIZE(applet_main), 1, applet_name_compare);
168         if (!p)
169                 return -1;
170         return p - applet_names;
171 #else
172         /* A version which does not pull in bsearch */
173         int i = 0;
174         const char *p = applet_names;
175         while (i < NUM_APPLETS) {
176                 if (strcmp(name, p) == 0)
177                         return i;
178                 p += strlen(p) + 1;
179                 i++;
180         }
181         return -1;
182 #endif
183 }
184
185
186 void lbb_prepare(const char *applet
187                 IF_FEATURE_INDIVIDUAL(, char **argv))
188                                 MAIN_EXTERNALLY_VISIBLE;
189 void lbb_prepare(const char *applet
190                 IF_FEATURE_INDIVIDUAL(, char **argv))
191 {
192 #ifdef __GLIBC__
193         (*(int **)&bb_errno) = __errno_location();
194         barrier();
195 #endif
196         applet_name = applet;
197
198         /* Set locale for everybody except 'init' */
199         if (ENABLE_LOCALE_SUPPORT && getpid() != 1)
200                 setlocale(LC_ALL, "");
201
202 #if ENABLE_FEATURE_INDIVIDUAL
203         /* Redundant for busybox (run_applet_and_exit covers that case)
204          * but needed for "individual applet" mode */
205         if (argv[1] && !argv[2] && strcmp(argv[1], "--help") == 0) {
206                 /* Special case. POSIX says "test --help"
207                  * should be no different from e.g. "test --foo".  */
208                 if (!ENABLE_TEST || strcmp(applet_name, "test") != 0)
209                         bb_show_usage();
210         }
211 #endif
212 }
213
214 /* The code below can well be in applets/applets.c, as it is used only
215  * for busybox binary, not "individual" binaries.
216  * However, keeping it here and linking it into libbusybox.so
217  * (together with remaining tiny applets/applets.o)
218  * makes it possible to avoid --whole-archive at link time.
219  * This makes (shared busybox) + libbusybox smaller.
220  * (--gc-sections would be even better....)
221  */
222
223 const char *applet_name;
224 #if !BB_MMU
225 bool re_execed;
226 #endif
227
228
229 /* If not built as a single-applet executable... */
230 #if !defined(SINGLE_APPLET_MAIN)
231
232 IF_FEATURE_SUID(static uid_t ruid;)  /* real uid */
233
234 #if ENABLE_FEATURE_SUID_CONFIG
235
236 /* applets[] is const, so we have to define this "override" structure */
237 static struct BB_suid_config {
238         int m_applet;
239         uid_t m_uid;
240         gid_t m_gid;
241         mode_t m_mode;
242         struct BB_suid_config *m_next;
243 } *suid_config;
244
245 static bool suid_cfg_readable;
246
247 /* check if u is member of group g */
248 static int ingroup(uid_t u, gid_t g)
249 {
250         struct group *grp = getgrgid(g);
251
252         if (grp) {
253                 char **mem;
254
255                 for (mem = grp->gr_mem; *mem; mem++) {
256                         struct passwd *pwd = getpwnam(*mem);
257
258                         if (pwd && (pwd->pw_uid == u))
259                                 return 1;
260                 }
261         }
262         return 0;
263 }
264
265 /* This should probably be a libbb routine.  In that case,
266  * I'd probably rename it to something like bb_trimmed_slice.
267  */
268 static char *get_trimmed_slice(char *s, char *e)
269 {
270         /* First, consider the value at e to be nul and back up until we
271          * reach a non-space char.  Set the char after that (possibly at
272          * the original e) to nul. */
273         while (e-- > s) {
274                 if (!isspace(*e)) {
275                         break;
276                 }
277         }
278         e[1] = '\0';
279
280         /* Next, advance past all leading space and return a ptr to the
281          * first non-space char; possibly the terminating nul. */
282         return skip_whitespace(s);
283 }
284
285 /* Don't depend on the tools to combine strings. */
286 static const char config_file[] ALIGN1 = "/etc/busybox.conf";
287
288 /* We don't supply a value for the nul, so an index adjustment is
289  * necessary below.  Also, we use unsigned short here to save some
290  * space even though these are really mode_t values. */
291 static const unsigned short mode_mask[] ALIGN2 = {
292         /*  SST     sst                 xxx         --- */
293         S_ISUID,    S_ISUID|S_IXUSR,    S_IXUSR,    0,  /* user */
294         S_ISGID,    S_ISGID|S_IXGRP,    S_IXGRP,    0,  /* group */
295         0,          S_IXOTH,            S_IXOTH,    0   /* other */
296 };
297
298 #define parse_error(x)  do { errmsg = x; goto pe_label; } while (0)
299
300 static void parse_config_file(void)
301 {
302         struct BB_suid_config *sct_head;
303         struct BB_suid_config *sct;
304         int applet_no;
305         FILE *f;
306         const char *errmsg;
307         char *s;
308         char *e;
309         int i;
310         unsigned lc;
311         smallint section;
312         char buffer[256];
313         struct stat st;
314
315         assert(!suid_config); /* Should be set to NULL by bss init. */
316
317         ruid = getuid();
318         if (ruid == 0) /* run by root - don't need to even read config file */
319                 return;
320
321         if ((stat(config_file, &st) != 0)       /* No config file? */
322          || !S_ISREG(st.st_mode)                /* Not a regular file? */
323          || (st.st_uid != 0)                    /* Not owned by root? */
324          || (st.st_mode & (S_IWGRP | S_IWOTH))  /* Writable by non-root? */
325          || !(f = fopen_for_read(config_file))      /* Cannot open? */
326         ) {
327                 return;
328         }
329
330         suid_cfg_readable = 1;
331         sct_head = NULL;
332         section = lc = 0;
333
334         while (1) {
335                 s = buffer;
336
337                 if (!fgets(s, sizeof(buffer), f)) { /* Are we done? */
338 // why?
339                         if (ferror(f)) {   /* Make sure it wasn't a read error. */
340                                 parse_error("reading");
341                         }
342                         fclose(f);
343                         suid_config = sct_head; /* Success, so set the pointer. */
344                         return;
345                 }
346
347                 lc++;                                   /* Got a (partial) line. */
348
349                 /* If a line is too long for our buffer, we consider it an error.
350                  * The following test does mistreat one corner case though.
351                  * If the final line of the file does not end with a newline and
352                  * yet exactly fills the buffer, it will be treated as too long
353                  * even though there isn't really a problem.  But it isn't really
354                  * worth adding code to deal with such an unlikely situation, and
355                  * we do err on the side of caution.  Besides, the line would be
356                  * too long if it did end with a newline. */
357                 if (!strchr(s, '\n') && !feof(f)) {
358                         parse_error("line too long");
359                 }
360
361                 /* Trim leading and trailing whitespace, ignoring comments, and
362                  * check if the resulting string is empty. */
363                 s = get_trimmed_slice(s, strchrnul(s, '#'));
364                 if (!*s) {
365                         continue;
366                 }
367
368                 /* Check for a section header. */
369
370                 if (*s == '[') {
371                         /* Unlike the old code, we ignore leading and trailing
372                          * whitespace for the section name.  We also require that
373                          * there are no stray characters after the closing bracket. */
374                         e = strchr(s, ']');
375                         if (!e   /* Missing right bracket? */
376                          || e[1] /* Trailing characters? */
377                          || !*(s = get_trimmed_slice(s+1, e)) /* Missing name? */
378                         ) {
379                                 parse_error("section header");
380                         }
381                         /* Right now we only have one section so just check it.
382                          * If more sections are added in the future, please don't
383                          * resort to cascading ifs with multiple strcasecmp calls.
384                          * That kind of bloated code is all too common.  A loop
385                          * and a string table would be a better choice unless the
386                          * number of sections is very small. */
387                         if (strcasecmp(s, "SUID") == 0) {
388                                 section = 1;
389                                 continue;
390                         }
391                         section = -1;   /* Unknown section so set to skip. */
392                         continue;
393                 }
394
395                 /* Process sections. */
396
397                 if (section == 1) {             /* SUID */
398                         /* Since we trimmed leading and trailing space above, we're
399                          * now looking for strings of the form
400                          *    <key>[::space::]*=[::space::]*<value>
401                          * where both key and value could contain inner whitespace. */
402
403                         /* First get the key (an applet name in our case). */
404                         e = strchr(s, '=');
405                         if (e) {
406                                 s = get_trimmed_slice(s, e);
407                         }
408                         if (!e || !*s) {        /* Missing '=' or empty key. */
409                                 parse_error("keyword");
410                         }
411
412                         /* Ok, we have an applet name.  Process the rhs if this
413                          * applet is currently built in and ignore it otherwise.
414                          * Note: this can hide config file bugs which only pop
415                          * up when the busybox configuration is changed. */
416                         applet_no = find_applet_by_name(s);
417                         if (applet_no >= 0) {
418                                 /* Note: We currently don't check for duplicates!
419                                  * The last config line for each applet will be the
420                                  * one used since we insert at the head of the list.
421                                  * I suppose this could be considered a feature. */
422                                 sct = xmalloc(sizeof(struct BB_suid_config));
423                                 sct->m_applet = applet_no;
424                                 sct->m_mode = 0;
425                                 sct->m_next = sct_head;
426                                 sct_head = sct;
427
428                                 /* Get the specified mode. */
429
430                                 e = skip_whitespace(e+1);
431
432                                 for (i = 0; i < 3; i++) {
433                                         /* There are 4 chars + 1 nul for each of user/group/other. */
434                                         static const char mode_chars[] ALIGN1 = "Ssx-\0" "Ssx-\0" "Ttx-";
435
436                                         const char *q;
437                                         q = strchrnul(mode_chars + 5*i, *e++);
438                                         if (!*q) {
439                                                 parse_error("mode");
440                                         }
441                                         /* Adjust by -i to account for nul. */
442                                         sct->m_mode |= mode_mask[(q - mode_chars) - i];
443                                 }
444
445                                 /* Now get the the user/group info. */
446
447                                 s = skip_whitespace(e);
448
449                                 /* Note: we require whitespace between the mode and the
450                                  * user/group info. */
451                                 if ((s == e) || !(e = strchr(s, '.'))) {
452                                         parse_error("<uid>.<gid>");
453                                 }
454                                 *e++ = '\0';
455
456                                 /* We can't use get_ug_id here since it would exit()
457                                  * if a uid or gid was not found.  Oh well... */
458                                 sct->m_uid = bb_strtoul(s, NULL, 10);
459                                 if (errno) {
460                                         struct passwd *pwd = getpwnam(s);
461                                         if (!pwd) {
462                                                 parse_error("user");
463                                         }
464                                         sct->m_uid = pwd->pw_uid;
465                                 }
466
467                                 sct->m_gid = bb_strtoul(e, NULL, 10);
468                                 if (errno) {
469                                         struct group *grp;
470                                         grp = getgrnam(e);
471                                         if (!grp) {
472                                                 parse_error("group");
473                                         }
474                                         sct->m_gid = grp->gr_gid;
475                                 }
476                         }
477                         continue;
478                 }
479
480                 /* Unknown sections are ignored. */
481
482                 /* Encountering configuration lines prior to seeing a
483                  * section header is treated as an error.  This is how
484                  * the old code worked, but it may not be desirable.
485                  * We may want to simply ignore such lines in case they
486                  * are used in some future version of busybox. */
487                 if (!section) {
488                         parse_error("keyword outside section");
489                 }
490
491         } /* while (1) */
492
493  pe_label:
494         fprintf(stderr, "Parse error in %s, line %d: %s\n",
495                         config_file, lc, errmsg);
496
497         fclose(f);
498         /* Release any allocated memory before returning. */
499         while (sct_head) {
500                 sct = sct_head->m_next;
501                 free(sct_head);
502                 sct_head = sct;
503         }
504 }
505 #else
506 static inline void parse_config_file(void)
507 {
508         IF_FEATURE_SUID(ruid = getuid();)
509 }
510 #endif /* FEATURE_SUID_CONFIG */
511
512
513 #if ENABLE_FEATURE_SUID
514 static void check_suid(int applet_no)
515 {
516         gid_t rgid;  /* real gid */
517
518         if (ruid == 0) /* set by parse_config_file() */
519                 return; /* run by root - no need to check more */
520         rgid = getgid();
521
522 #if ENABLE_FEATURE_SUID_CONFIG
523         if (suid_cfg_readable) {
524                 uid_t uid;
525                 struct BB_suid_config *sct;
526                 mode_t m;
527
528                 for (sct = suid_config; sct; sct = sct->m_next) {
529                         if (sct->m_applet == applet_no)
530                                 goto found;
531                 }
532                 goto check_need_suid;
533  found:
534                 m = sct->m_mode;
535                 if (sct->m_uid == ruid)
536                         /* same uid */
537                         m >>= 6;
538                 else if ((sct->m_gid == rgid) || ingroup(ruid, sct->m_gid))
539                         /* same group / in group */
540                         m >>= 3;
541
542                 if (!(m & S_IXOTH))           /* is x bit not set ? */
543                         bb_error_msg_and_die("you have no permission to run this applet!");
544
545                 /* _both_ sgid and group_exec have to be set for setegid */
546                 if ((sct->m_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
547                         rgid = sct->m_gid;
548                 /* else (no setegid) we will set egid = rgid */
549
550                 /* We set effective AND saved ids. If saved-id is not set
551                  * like we do below, seteiud(0) can still later succeed! */
552                 if (setresgid(-1, rgid, rgid))
553                         bb_perror_msg_and_die("setresgid");
554
555                 /* do we have to set effective uid? */
556                 uid = ruid;
557                 if (sct->m_mode & S_ISUID)
558                         uid = sct->m_uid;
559                 /* else (no seteuid) we will set euid = ruid */
560
561                 if (setresuid(-1, uid, uid))
562                         bb_perror_msg_and_die("setresuid");
563                 return;
564         }
565 #if !ENABLE_FEATURE_SUID_CONFIG_QUIET
566         {
567                 static bool onetime = 0;
568
569                 if (!onetime) {
570                         onetime = 1;
571                         fprintf(stderr, "Using fallback suid method\n");
572                 }
573         }
574 #endif
575  check_need_suid:
576 #endif
577         if (APPLET_SUID(applet_no) == _BB_SUID_REQUIRE) {
578                 /* Real uid is not 0. If euid isn't 0 too, suid bit
579                  * is most probably not set on our executable */
580                 if (geteuid())
581                         bb_error_msg_and_die("must be suid to work properly");
582         } else if (APPLET_SUID(applet_no) == _BB_SUID_DROP) {
583                 xsetgid(rgid);  /* drop all privileges */
584                 xsetuid(ruid);
585         }
586 }
587 #else
588 #define check_suid(x) ((void)0)
589 #endif /* FEATURE_SUID */
590
591
592 #if ENABLE_FEATURE_INSTALLER
593 static const char usr_bin [] ALIGN1 = "/usr/bin/";
594 static const char usr_sbin[] ALIGN1 = "/usr/sbin/";
595 static const char *const install_dir[] = {
596         &usr_bin [8], /* "/" */
597         &usr_bin [4], /* "/bin/" */
598         &usr_sbin[4], /* "/sbin/" */
599         usr_bin,
600         usr_sbin
601 };
602
603
604 /* create (sym)links for each applet */
605 static void install_links(const char *busybox, int use_symbolic_links,
606                 char *custom_install_dir)
607 {
608         /* directory table
609          * this should be consistent w/ the enum,
610          * busybox.h::bb_install_loc_t, or else... */
611         int (*lf)(const char *, const char *);
612         char *fpc;
613         unsigned i;
614         int rc;
615
616         lf = link;
617         if (use_symbolic_links)
618                 lf = symlink;
619
620         for (i = 0; i < ARRAY_SIZE(applet_main); i++) {
621                 fpc = concat_path_file(
622                                 custom_install_dir ? custom_install_dir : install_dir[APPLET_INSTALL_LOC(i)],
623                                 APPLET_NAME(i));
624                 // debug: bb_error_msg("%slinking %s to busybox",
625                 //              use_symbolic_links ? "sym" : "", fpc);
626                 rc = lf(busybox, fpc);
627                 if (rc != 0 && errno != EEXIST) {
628                         bb_simple_perror_msg(fpc);
629                 }
630                 free(fpc);
631         }
632 }
633 #else
634 # define install_links(x,y,z) ((void)0)
635 #endif
636
637 /* If we were called as "busybox..." */
638 static int busybox_main(char **argv)
639 {
640         if (!argv[1]) {
641                 /* Called without arguments */
642                 const char *a;
643                 int col;
644                 unsigned output_width;
645  help:
646                 output_width = 80;
647                 if (ENABLE_FEATURE_AUTOWIDTH) {
648                         /* Obtain the terminal width */
649                         get_terminal_width_height(0, &output_width, NULL);
650                 }
651
652                 dup2(1, 2);
653                 full_write2_str(bb_banner); /* reuse const string */
654                 full_write2_str(" multi-call binary.\n"); /* reuse */
655                 full_write2_str(
656                         "Copyright (C) 1998-2009 Erik Andersen, Rob Landley, Denys Vlasenko\n"
657                         "and others. Licensed under GPLv2.\n"
658                         "See source distribution for full notice.\n"
659                         "\n"
660                         "Usage: busybox [function] [arguments]...\n"
661                         "   or: function [arguments]...\n"
662                         "\n"
663                         "\tBusyBox is a multi-call binary that combines many common Unix\n"
664                         "\tutilities into a single executable.  Most people will create a\n"
665                         "\tlink to busybox for each function they wish to use and BusyBox\n"
666                         "\twill act like whatever it was invoked as.\n"
667                         "\n"
668                         "Currently defined functions:\n"
669                 );
670                 col = 0;
671                 a = applet_names;
672                 /* prevent last comma to be in the very last pos */
673                 output_width--;
674                 while (*a) {
675                         int len2 = strlen(a) + 2;
676                         if (col >= (int)output_width - len2) {
677                                 full_write2_str(",\n");
678                                 col = 0;
679                         }
680                         if (col == 0) {
681                                 col = 6;
682                                 full_write2_str("\t");
683                         } else {
684                                 full_write2_str(", ");
685                         }
686                         full_write2_str(a);
687                         col += len2;
688                         a += len2 - 1;
689                 }
690                 full_write2_str("\n\n");
691                 return 0;
692         }
693
694         if (strncmp(argv[1], "--list", 6) == 0) {
695                 unsigned i = 0;
696                 const char *a = applet_names;
697                 dup2(1, 2);
698                 while (*a) {
699 #if ENABLE_FEATURE_INSTALLER
700                         if (argv[1][6]) /* --list-path? */
701                                 full_write2_str(install_dir[APPLET_INSTALL_LOC(i)] + 1);
702 #endif
703                         full_write2_str(a);
704                         full_write2_str("\n");
705                         i++;
706                         a += strlen(a) + 1;
707                 }
708                 return 0;
709         }
710
711         if (ENABLE_FEATURE_INSTALLER && strcmp(argv[1], "--install") == 0) {
712                 int use_symbolic_links;
713                 const char *busybox;
714                 busybox = xmalloc_readlink(bb_busybox_exec_path);
715                 if (!busybox)
716                         busybox = bb_busybox_exec_path;
717                 /* busybox --install [-s] [DIR]: */
718                 /* -s: make symlinks */
719                 /* DIR: directory to install links to */
720                 use_symbolic_links = (argv[2] && strcmp(argv[2], "-s") == 0 && argv++);
721                 install_links(busybox, use_symbolic_links, argv[2]);
722                 return 0;
723         }
724
725         if (strcmp(argv[1], "--help") == 0) {
726                 /* "busybox --help [<applet>]" */
727                 if (!argv[2])
728                         goto help;
729                 /* convert to "<applet> --help" */
730                 argv[0] = argv[2];
731                 argv[2] = NULL;
732         } else {
733                 /* "busybox <applet> arg1 arg2 ..." */
734                 argv++;
735         }
736         /* We support "busybox /a/path/to/applet args..." too. Allows for
737          * "#!/bin/busybox"-style wrappers */
738         applet_name = bb_get_last_path_component_nostrip(argv[0]);
739         run_applet_and_exit(applet_name, argv);
740
741         /*bb_error_msg_and_die("applet not found"); - sucks in printf */
742         full_write2_str(applet_name);
743         full_write2_str(": applet not found\n");
744         xfunc_die();
745 }
746
747 void FAST_FUNC run_applet_no_and_exit(int applet_no, char **argv)
748 {
749         int argc = 1;
750
751         while (argv[argc])
752                 argc++;
753
754         /* Reinit some shared global data */
755         xfunc_error_retval = EXIT_FAILURE;
756
757         applet_name = APPLET_NAME(applet_no);
758         if (argc == 2 && strcmp(argv[1], "--help") == 0) {
759                 /* Special case. POSIX says "test --help"
760                  * should be no different from e.g. "test --foo".  */
761 //TODO: just compare applet_no with APPLET_NO_test
762                 if (!ENABLE_TEST || strcmp(applet_name, "test") != 0)
763                         bb_show_usage();
764         }
765         if (ENABLE_FEATURE_SUID)
766                 check_suid(applet_no);
767         exit(applet_main[applet_no](argc, argv));
768 }
769
770 void FAST_FUNC run_applet_and_exit(const char *name, char **argv)
771 {
772         int applet = find_applet_by_name(name);
773         if (applet >= 0)
774                 run_applet_no_and_exit(applet, argv);
775         if (!strncmp(name, "busybox", 7))
776                 exit(busybox_main(argv));
777 }
778
779 #endif /* !defined(SINGLE_APPLET_MAIN) */
780
781
782
783 #if ENABLE_BUILD_LIBBUSYBOX
784 int lbb_main(char **argv)
785 #else
786 int main(int argc UNUSED_PARAM, char **argv)
787 #endif
788 {
789         /* Tweak malloc for reduced memory consumption */
790 #ifndef PAGE_SIZE
791 # define PAGE_SIZE (4*1024) /* guess */
792 #endif
793 #ifdef M_TRIM_THRESHOLD
794         /* M_TRIM_THRESHOLD is the maximum amount of freed top-most memory
795          * to keep before releasing to the OS
796          * Default is way too big: 256k
797          */
798         mallopt(M_TRIM_THRESHOLD, 2 * PAGE_SIZE);
799 #endif
800 #ifdef M_MMAP_THRESHOLD
801         /* M_MMAP_THRESHOLD is the request size threshold for using mmap()
802          * Default is too big: 256k
803          */
804         mallopt(M_MMAP_THRESHOLD, 8 * PAGE_SIZE - 256);
805 #endif
806
807 #if defined(SINGLE_APPLET_MAIN)
808         /* Only one applet is selected by the user! */
809         /* applet_names in this case is just "applet\0\0" */
810         lbb_prepare(applet_names IF_FEATURE_INDIVIDUAL(, argv));
811         return SINGLE_APPLET_MAIN(argc, argv);
812 #else
813         lbb_prepare("busybox" IF_FEATURE_INDIVIDUAL(, argv));
814
815 #if !BB_MMU
816         /* NOMMU re-exec trick sets high-order bit in first byte of name */
817         if (argv[0][0] & 0x80) {
818                 re_execed = 1;
819                 argv[0][0] &= 0x7f;
820         }
821 #endif
822         applet_name = argv[0];
823         if (applet_name[0] == '-')
824                 applet_name++;
825         applet_name = bb_basename(applet_name);
826
827         parse_config_file(); /* ...maybe, if FEATURE_SUID_CONFIG */
828
829         run_applet_and_exit(applet_name, argv);
830
831         /*bb_error_msg_and_die("applet not found"); - sucks in printf */
832         full_write2_str(applet_name);
833         full_write2_str(": applet not found\n");
834         xfunc_die();
835 #endif
836 }