ash: allow shell scripts to be embedded in the binary
[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 GPL.
11  *
12  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
13  */
14 /* We are trying to not use printf, this benefits the case when selected
15  * applets are really simple. Example:
16  *
17  * $ ./busybox
18  * ...
19  * Currently defined functions:
20  *         basename, false, true
21  *
22  * $ size busybox
23  *    text    data     bss     dec     hex filename
24  *    4473      52      72    4597    11f5 busybox
25  *
26  * FEATURE_INSTALLER or FEATURE_SUID will still link printf routines in. :(
27  */
28 #include "busybox.h"
29
30 #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
31     || defined(__APPLE__) \
32     )
33 # include <malloc.h> /* for mallopt */
34 #endif
35
36 /* Declare <applet>_main() */
37 #define PROTOTYPES
38 #include "applets.h"
39 #undef PROTOTYPES
40
41 /* Include generated applet names, pointers to <applet>_main, etc */
42 #include "applet_tables.h"
43 /* ...and if applet_tables generator says we have only one applet... */
44 #ifdef SINGLE_APPLET_MAIN
45 # undef ENABLE_FEATURE_INDIVIDUAL
46 # define ENABLE_FEATURE_INDIVIDUAL 1
47 # undef IF_FEATURE_INDIVIDUAL
48 # define IF_FEATURE_INDIVIDUAL(...) __VA_ARGS__
49 #endif
50
51 #include "usage_compressed.h"
52
53 #if ENABLE_ASH_EMBEDDED_SCRIPTS
54 # define DEFINE_script_names 1
55 # include "embedded_scripts.h"
56 #else
57 # define NUM_SCRIPTS 0
58 #endif
59 #if NUM_SCRIPTS > 0
60 # include "bb_archive.h"
61 static const char packed_scripts[] ALIGN1 = { PACKED_SCRIPTS };
62 #endif
63
64 /* "Do not compress usage text if uncompressed text is small
65  *  and we don't include bunzip2 code for other reasons"
66  *
67  * Useful for mass one-applet rebuild (bunzip2 code is ~2.7k).
68  *
69  * Unlike BUNZIP2, if FEATURE_SEAMLESS_BZ2 is on, bunzip2 code is built but
70  * still may be unused if none of the selected applets calls open_zipped()
71  * or its friends; we test for (FEATURE_SEAMLESS_BZ2 && <APPLET>) instead.
72  * For example, only if TAR and FEATURE_SEAMLESS_BZ2 are both selected,
73  * then bunzip2 code will be linked in anyway, and disabling help compression
74  * would be not optimal:
75  */
76 #if UNPACKED_USAGE_LENGTH < 4*1024 \
77  && !(ENABLE_FEATURE_SEAMLESS_BZ2 && ENABLE_TAR) \
78  && !(ENABLE_FEATURE_SEAMLESS_BZ2 && ENABLE_MODPROBE) \
79  && !(ENABLE_FEATURE_SEAMLESS_BZ2 && ENABLE_INSMOD) \
80  && !(ENABLE_FEATURE_SEAMLESS_BZ2 && ENABLE_DEPMOD) \
81  && !(ENABLE_FEATURE_SEAMLESS_BZ2 && ENABLE_MAN) \
82  && !ENABLE_BUNZIP2 \
83  && !ENABLE_BZCAT
84 # undef  ENABLE_FEATURE_COMPRESS_USAGE
85 # define ENABLE_FEATURE_COMPRESS_USAGE 0
86 #endif
87
88
89 unsigned FAST_FUNC string_array_len(char **argv)
90 {
91         char **start = argv;
92
93         while (*argv)
94                 argv++;
95
96         return argv - start;
97 }
98
99
100 #if ENABLE_SHOW_USAGE && !ENABLE_FEATURE_COMPRESS_USAGE
101 static const char usage_messages[] ALIGN1 = UNPACKED_USAGE;
102 #else
103 # define usage_messages 0
104 #endif
105
106 #if ENABLE_FEATURE_COMPRESS_USAGE
107
108 static const char packed_usage[] ALIGN1 = { PACKED_USAGE };
109 # include "bb_archive.h"
110 static const char *unpack_usage_messages(void)
111 {
112         char *outbuf = NULL;
113         bunzip_data *bd;
114         int i;
115         jmp_buf jmpbuf;
116
117         /* Setup for I/O error handling via longjmp */
118         i = setjmp(jmpbuf);
119         if (i == 0) {
120                 i = start_bunzip(&jmpbuf,
121                         &bd,
122                         /* src_fd: */ -1,
123                         /* inbuf:  */ packed_usage,
124                         /* len:    */ sizeof(packed_usage)
125                 );
126         }
127         /* read_bunzip can longjmp and end up here with i != 0
128          * on read data errors! Not trivial */
129         if (i == 0) {
130                 /* Cannot use xmalloc: will leak bd in NOFORK case! */
131                 outbuf = malloc_or_warn(sizeof(UNPACKED_USAGE));
132                 if (outbuf)
133                         read_bunzip(bd, outbuf, sizeof(UNPACKED_USAGE));
134         }
135         dealloc_bunzip(bd);
136         return outbuf;
137 }
138 # define dealloc_usage_messages(s) free(s)
139
140 #else
141
142 # define unpack_usage_messages() usage_messages
143 # define dealloc_usage_messages(s) ((void)(s))
144
145 #endif /* FEATURE_COMPRESS_USAGE */
146
147
148 void FAST_FUNC bb_show_usage(void)
149 {
150         if (ENABLE_SHOW_USAGE) {
151 #ifdef SINGLE_APPLET_STR
152                 /* Imagine that this applet is "true". Dont suck in printf! */
153                 const char *usage_string = unpack_usage_messages();
154
155                 if (*usage_string == '\b') {
156                         full_write2_str("No help available.\n\n");
157                 } else {
158                         full_write2_str("Usage: "SINGLE_APPLET_STR" ");
159                         full_write2_str(usage_string);
160                         full_write2_str("\n\n");
161                 }
162                 if (ENABLE_FEATURE_CLEAN_UP)
163                         dealloc_usage_messages((char*)usage_string);
164 #else
165                 const char *p;
166                 const char *usage_string = p = unpack_usage_messages();
167                 int ap = find_applet_by_name(applet_name);
168
169                 if (ap < 0) /* never happens, paranoia */
170                         xfunc_die();
171                 while (ap) {
172                         while (*p++) continue;
173                         ap--;
174                 }
175                 full_write2_str(bb_banner);
176                 full_write2_str(" multi-call binary.\n");
177                 if (*p == '\b')
178                         full_write2_str("\nNo help available.\n\n");
179                 else {
180                         full_write2_str("\nUsage: ");
181                         full_write2_str(applet_name);
182                         if (p[0]) {
183                                 if (p[0] != '\n')
184                                         full_write2_str(" ");
185                                 full_write2_str(p);
186                         }
187                         full_write2_str("\n");
188                 }
189                 if (ENABLE_FEATURE_CLEAN_UP)
190                         dealloc_usage_messages((char*)usage_string);
191 #endif
192         }
193         xfunc_die();
194 }
195
196 int FAST_FUNC find_applet_by_name(const char *name)
197 {
198         unsigned i, max;
199         int j;
200         const char *p;
201
202 /* The commented-out word-at-a-time code is ~40% faster, but +160 bytes.
203  * "Faster" here saves ~0.5 microsecond of real time - not worth it.
204  */
205 #if 0 /*BB_UNALIGNED_MEMACCESS_OK && BB_LITTLE_ENDIAN*/
206         uint32_t n32;
207
208         /* Handle all names < 2 chars long early */
209         if (name[0] == '\0')
210                 return -1; /* "" is not a valid applet name */
211         if (name[1] == '\0') {
212                 if (!ENABLE_TEST)
213                         return -1; /* 1-char name is not valid */
214                 if (name[0] != ']')
215                         return -1; /* 1-char name which isn't "[" is not valid */
216                 /* applet "[" is always applet #0: */
217                 return 0;
218         }
219 #endif
220
221         p = applet_names;
222         i = 0;
223 #if KNOWN_APPNAME_OFFSETS <= 0
224         max = NUM_APPLETS;
225 #else
226         max = NUM_APPLETS * KNOWN_APPNAME_OFFSETS;
227         for (j = ARRAY_SIZE(applet_nameofs)-1; j >= 0; j--) {
228                 const char *pp = applet_names + applet_nameofs[j];
229                 if (strcmp(name, pp) >= 0) {
230                         //bb_error_msg("name:'%s' >= pp:'%s'", name, pp);
231                         p = pp;
232                         i = max - NUM_APPLETS;
233                         break;
234                 }
235                 max -= NUM_APPLETS;
236         }
237         max /= (unsigned)KNOWN_APPNAME_OFFSETS;
238         i /= (unsigned)KNOWN_APPNAME_OFFSETS;
239         //bb_error_msg("name:'%s' starting from:'%s' i:%u max:%u", name, p, i, max);
240 #endif
241
242         /* Open-coded linear search without strcmp/strlen calls for speed */
243
244 #if 0 /*BB_UNALIGNED_MEMACCESS_OK && BB_LITTLE_ENDIAN*/
245         /* skip "[\0" name, it's surely not it */
246         if (ENABLE_TEST && LONE_CHAR(p, '['))
247                 i++, p += 2;
248         /* All remaining applet names in p[] are at least 2 chars long */
249         /* name[] is also at least 2 chars long */
250
251         n32 = (name[0] << 0) | (name[1] << 8) | (name[2] << 16);
252         while (i < max) {
253                 uint32_t p32;
254                 char ch;
255
256                 /* Quickly check match of the first 3 bytes */
257                 move_from_unaligned32(p32, p);
258                 p += 3;
259                 if ((p32 & 0x00ffffff) != n32) {
260                         /* Most likely case: 3 first bytes do not match */
261                         i++;
262                         if ((p32 & 0x00ff0000) == '\0')
263                                 continue; // p[2] was NUL
264                         p++;
265                         if ((p32 & 0xff000000) == '\0')
266                                 continue; // p[3] was NUL
267                         /* p[0..3] aren't matching and none is NUL, check the rest */
268                         while (*p++ != '\0')
269                                 continue;
270                         continue;
271                 }
272
273                 /* Unlikely branch: first 3 bytes ([0..2]) match */
274                 if ((p32 & 0x00ff0000) == '\0') {
275                         /* name is 2-byte long, it is full match */
276                         //bb_error_msg("found:'%s' i:%u", name, i);
277                         return i;
278                 }
279                 /* Check remaining bytes [3..NUL] */
280                 ch = (p32 >> 24);
281                 j = 3;
282                 while (ch == name[j]) {
283                         if (ch == '\0') {
284                                 //bb_error_msg("found:'%s' i:%u", name, i);
285                                 return i;
286                         }
287                         ch = *++p;
288                         j++;
289                 }
290                 /* Not a match. Skip it, including NUL */
291                 while (ch != '\0')
292                         ch = *++p;
293                 p++;
294                 i++;
295         }
296         return -1;
297 #else
298         while (i < max) {
299                 char ch;
300                 j = 0;
301                 /* Do we see "name\0" in applet_names[p] position? */
302                 while ((ch = *p) == name[j]) {
303                         if (ch == '\0') {
304                                 //bb_error_msg("found:'%s' i:%u", name, i);
305                                 return i; /* yes */
306                         }
307                         p++;
308                         j++;
309                 }
310                 /* No.
311                  * p => 1st non-matching char in applet_names[],
312                  * skip to and including NUL.
313                  */
314                 while (ch != '\0')
315                         ch = *++p;
316                 p++;
317                 i++;
318         }
319         return -1;
320 #endif
321 }
322
323
324 void lbb_prepare(const char *applet
325                 IF_FEATURE_INDIVIDUAL(, char **argv))
326                                 MAIN_EXTERNALLY_VISIBLE;
327 void lbb_prepare(const char *applet
328                 IF_FEATURE_INDIVIDUAL(, char **argv))
329 {
330 #ifdef __GLIBC__
331         (*(int **)&bb_errno) = __errno_location();
332         barrier();
333 #endif
334         applet_name = applet;
335
336         if (ENABLE_LOCALE_SUPPORT)
337                 setlocale(LC_ALL, "");
338
339 #if ENABLE_FEATURE_INDIVIDUAL
340         /* Redundant for busybox (run_applet_and_exit covers that case)
341          * but needed for "individual applet" mode */
342         if (argv[1]
343          && !argv[2]
344          && strcmp(argv[1], "--help") == 0
345          && !is_prefixed_with(applet, "busybox")
346         ) {
347                 /* Special case. POSIX says "test --help"
348                  * should be no different from e.g. "test --foo".  */
349                 if (!ENABLE_TEST || strcmp(applet_name, "test") != 0)
350                         bb_show_usage();
351         }
352 #endif
353 }
354
355 /* The code below can well be in applets/applets.c, as it is used only
356  * for busybox binary, not "individual" binaries.
357  * However, keeping it here and linking it into libbusybox.so
358  * (together with remaining tiny applets/applets.o)
359  * makes it possible to avoid --whole-archive at link time.
360  * This makes (shared busybox) + libbusybox smaller.
361  * (--gc-sections would be even better....)
362  */
363
364 const char *applet_name;
365 #if !BB_MMU
366 bool re_execed;
367 #endif
368
369
370 /* If not built as a single-applet executable... */
371 #if !defined(SINGLE_APPLET_MAIN)
372
373 IF_FEATURE_SUID(static uid_t ruid;)  /* real uid */
374
375 # if ENABLE_FEATURE_SUID_CONFIG
376
377 static struct suid_config_t {
378         /* next ptr must be first: this struct needs to be llist-compatible */
379         struct suid_config_t *m_next;
380         struct bb_uidgid_t m_ugid;
381         int m_applet;
382         mode_t m_mode;
383 } *suid_config;
384
385 static bool suid_cfg_readable;
386
387 /* libbb candidate */
388 static char *get_trimmed_slice(char *s, char *e)
389 {
390         /* First, consider the value at e to be nul and back up until we
391          * reach a non-space char.  Set the char after that (possibly at
392          * the original e) to nul. */
393         while (e-- > s) {
394                 if (!isspace(*e)) {
395                         break;
396                 }
397         }
398         e[1] = '\0';
399
400         /* Next, advance past all leading space and return a ptr to the
401          * first non-space char; possibly the terminating nul. */
402         return skip_whitespace(s);
403 }
404
405 static void parse_config_file(void)
406 {
407         /* Don't depend on the tools to combine strings. */
408         static const char config_file[] ALIGN1 = "/etc/busybox.conf";
409
410         struct suid_config_t *sct_head;
411         int applet_no;
412         FILE *f;
413         const char *errmsg;
414         unsigned lc;
415         smallint section;
416         struct stat st;
417
418         ruid = getuid();
419         if (ruid == 0) /* run by root - don't need to even read config file */
420                 return;
421
422         if ((stat(config_file, &st) != 0)       /* No config file? */
423          || !S_ISREG(st.st_mode)                /* Not a regular file? */
424          || (st.st_uid != 0)                    /* Not owned by root? */
425          || (st.st_mode & (S_IWGRP | S_IWOTH))  /* Writable by non-root? */
426          || !(f = fopen_for_read(config_file))  /* Cannot open? */
427         ) {
428                 return;
429         }
430
431         suid_cfg_readable = 1;
432         sct_head = NULL;
433         section = lc = 0;
434
435         while (1) {
436                 char buffer[256];
437                 char *s;
438
439                 if (!fgets(buffer, sizeof(buffer), f)) { /* Are we done? */
440                         // Looks like bloat
441                         //if (ferror(f)) {   /* Make sure it wasn't a read error. */
442                         //      errmsg = "reading";
443                         //      goto pe_label;
444                         //}
445                         fclose(f);
446                         suid_config = sct_head; /* Success, so set the pointer. */
447                         return;
448                 }
449
450                 s = buffer;
451                 lc++;                                   /* Got a (partial) line. */
452
453                 /* If a line is too long for our buffer, we consider it an error.
454                  * The following test does mistreat one corner case though.
455                  * If the final line of the file does not end with a newline and
456                  * yet exactly fills the buffer, it will be treated as too long
457                  * even though there isn't really a problem.  But it isn't really
458                  * worth adding code to deal with such an unlikely situation, and
459                  * we do err on the side of caution.  Besides, the line would be
460                  * too long if it did end with a newline. */
461                 if (!strchr(s, '\n') && !feof(f)) {
462                         errmsg = "line too long";
463                         goto pe_label;
464                 }
465
466                 /* Trim leading and trailing whitespace, ignoring comments, and
467                  * check if the resulting string is empty. */
468                 s = get_trimmed_slice(s, strchrnul(s, '#'));
469                 if (!*s) {
470                         continue;
471                 }
472
473                 /* Check for a section header. */
474
475                 if (*s == '[') {
476                         /* Unlike the old code, we ignore leading and trailing
477                          * whitespace for the section name.  We also require that
478                          * there are no stray characters after the closing bracket. */
479                         char *e = strchr(s, ']');
480                         if (!e   /* Missing right bracket? */
481                          || e[1] /* Trailing characters? */
482                          || !*(s = get_trimmed_slice(s+1, e)) /* Missing name? */
483                         ) {
484                                 errmsg = "section header";
485                                 goto pe_label;
486                         }
487                         /* Right now we only have one section so just check it.
488                          * If more sections are added in the future, please don't
489                          * resort to cascading ifs with multiple strcasecmp calls.
490                          * That kind of bloated code is all too common.  A loop
491                          * and a string table would be a better choice unless the
492                          * number of sections is very small. */
493                         if (strcasecmp(s, "SUID") == 0) {
494                                 section = 1;
495                                 continue;
496                         }
497                         section = -1;   /* Unknown section so set to skip. */
498                         continue;
499                 }
500
501                 /* Process sections. */
502
503                 if (section == 1) {             /* SUID */
504                         /* Since we trimmed leading and trailing space above, we're
505                          * now looking for strings of the form
506                          *    <key>[::space::]*=[::space::]*<value>
507                          * where both key and value could contain inner whitespace. */
508
509                         /* First get the key (an applet name in our case). */
510                         char *e = strchr(s, '=');
511                         if (e) {
512                                 s = get_trimmed_slice(s, e);
513                         }
514                         if (!e || !*s) {        /* Missing '=' or empty key. */
515                                 errmsg = "keyword";
516                                 goto pe_label;
517                         }
518
519                         /* Ok, we have an applet name.  Process the rhs if this
520                          * applet is currently built in and ignore it otherwise.
521                          * Note: this can hide config file bugs which only pop
522                          * up when the busybox configuration is changed. */
523                         applet_no = find_applet_by_name(s);
524                         if (applet_no >= 0) {
525                                 unsigned i;
526                                 struct suid_config_t *sct;
527
528                                 /* Note: We currently don't check for duplicates!
529                                  * The last config line for each applet will be the
530                                  * one used since we insert at the head of the list.
531                                  * I suppose this could be considered a feature. */
532                                 sct = xzalloc(sizeof(*sct));
533                                 sct->m_applet = applet_no;
534                                 /*sct->m_mode = 0;*/
535                                 sct->m_next = sct_head;
536                                 sct_head = sct;
537
538                                 /* Get the specified mode. */
539
540                                 e = skip_whitespace(e+1);
541
542                                 for (i = 0; i < 3; i++) {
543                                         /* There are 4 chars for each of user/group/other.
544                                          * "x-xx" instead of "x-" are to make
545                                          * "idx > 3" check catch invalid chars.
546                                          */
547                                         static const char mode_chars[] ALIGN1 = "Ssx-" "Ssx-" "x-xx";
548                                         static const unsigned short mode_mask[] ALIGN2 = {
549                                                 S_ISUID, S_ISUID|S_IXUSR, S_IXUSR, 0, /* Ssx- */
550                                                 S_ISGID, S_ISGID|S_IXGRP, S_IXGRP, 0, /* Ssx- */
551                                                                           S_IXOTH, 0  /*   x- */
552                                         };
553                                         const char *q = strchrnul(mode_chars + 4*i, *e);
554                                         unsigned idx = q - (mode_chars + 4*i);
555                                         if (idx > 3) {
556                                                 errmsg = "mode";
557                                                 goto pe_label;
558                                         }
559                                         sct->m_mode |= mode_mask[q - mode_chars];
560                                         e++;
561                                 }
562
563                                 /* Now get the user/group info. */
564
565                                 s = skip_whitespace(e);
566                                 /* Default is 0.0, else parse USER.GROUP: */
567                                 if (*s) {
568                                         /* We require whitespace between mode and USER.GROUP */
569                                         if ((s == e) || !(e = strchr(s, '.'))) {
570                                                 errmsg = "uid.gid";
571                                                 goto pe_label;
572                                         }
573                                         *e = ':'; /* get_uidgid needs USER:GROUP syntax */
574                                         if (get_uidgid(&sct->m_ugid, s) == 0) {
575                                                 errmsg = "unknown user/group";
576                                                 goto pe_label;
577                                         }
578                                 }
579                         }
580                         continue;
581                 }
582
583                 /* Unknown sections are ignored. */
584
585                 /* Encountering configuration lines prior to seeing a
586                  * section header is treated as an error.  This is how
587                  * the old code worked, but it may not be desirable.
588                  * We may want to simply ignore such lines in case they
589                  * are used in some future version of busybox. */
590                 if (!section) {
591                         errmsg = "keyword outside section";
592                         goto pe_label;
593                 }
594         } /* while (1) */
595
596  pe_label:
597         fclose(f);
598         bb_error_msg("parse error in %s, line %u: %s", config_file, lc, errmsg);
599
600         /* Release any allocated memory before returning. */
601         llist_free((llist_t*)sct_head, NULL);
602 }
603 # else
604 static inline void parse_config_file(void)
605 {
606         IF_FEATURE_SUID(ruid = getuid();)
607 }
608 # endif /* FEATURE_SUID_CONFIG */
609
610
611 # if ENABLE_FEATURE_SUID && NUM_APPLETS > 0
612 #  if ENABLE_FEATURE_SUID_CONFIG
613 /* check if u is member of group g */
614 static int ingroup(uid_t u, gid_t g)
615 {
616         struct group *grp = getgrgid(g);
617         if (grp) {
618                 char **mem;
619                 for (mem = grp->gr_mem; *mem; mem++) {
620                         struct passwd *pwd = getpwnam(*mem);
621                         if (pwd && (pwd->pw_uid == u))
622                                 return 1;
623                 }
624         }
625         return 0;
626 }
627 #  endif
628
629 static void check_suid(int applet_no)
630 {
631         gid_t rgid;  /* real gid */
632
633         if (ruid == 0) /* set by parse_config_file() */
634                 return; /* run by root - no need to check more */
635         rgid = getgid();
636
637 #  if ENABLE_FEATURE_SUID_CONFIG
638         if (suid_cfg_readable) {
639                 uid_t uid;
640                 struct suid_config_t *sct;
641                 mode_t m;
642
643                 for (sct = suid_config; sct; sct = sct->m_next) {
644                         if (sct->m_applet == applet_no)
645                                 goto found;
646                 }
647                 goto check_need_suid;
648  found:
649                 /* Is this user allowed to run this applet? */
650                 m = sct->m_mode;
651                 if (sct->m_ugid.uid == ruid)
652                         /* same uid */
653                         m >>= 6;
654                 else if ((sct->m_ugid.gid == rgid) || ingroup(ruid, sct->m_ugid.gid))
655                         /* same group / in group */
656                         m >>= 3;
657                 if (!(m & S_IXOTH)) /* is x bit not set? */
658                         bb_error_msg_and_die("you have no permission to run this applet");
659
660                 /* We set effective AND saved ids. If saved-id is not set
661                  * like we do below, seteuid(0) can still later succeed! */
662
663                 /* Are we directed to change gid
664                  * (APPLET = *s* USER.GROUP or APPLET = *S* USER.GROUP)?
665                  */
666                 if (sct->m_mode & S_ISGID)
667                         rgid = sct->m_ugid.gid;
668                 /* else: we will set egid = rgid, thus dropping sgid effect */
669                 if (setresgid(-1, rgid, rgid))
670                         bb_perror_msg_and_die("setresgid");
671
672                 /* Are we directed to change uid
673                  * (APPLET = s** USER.GROUP or APPLET = S** USER.GROUP)?
674                  */
675                 uid = ruid;
676                 if (sct->m_mode & S_ISUID)
677                         uid = sct->m_ugid.uid;
678                 /* else: we will set euid = ruid, thus dropping suid effect */
679                 if (setresuid(-1, uid, uid))
680                         bb_perror_msg_and_die("setresuid");
681
682                 goto ret;
683         }
684 #   if !ENABLE_FEATURE_SUID_CONFIG_QUIET
685         {
686                 static bool onetime = 0;
687
688                 if (!onetime) {
689                         onetime = 1;
690                         bb_error_msg("using fallback suid method");
691                 }
692         }
693 #   endif
694  check_need_suid:
695 #  endif
696         if (APPLET_SUID(applet_no) == BB_SUID_REQUIRE) {
697                 /* Real uid is not 0. If euid isn't 0 too, suid bit
698                  * is most probably not set on our executable */
699                 if (geteuid())
700                         bb_error_msg_and_die("must be suid to work properly");
701         } else if (APPLET_SUID(applet_no) == BB_SUID_DROP) {
702                 /*
703                  * Drop all privileges.
704                  *
705                  * Don't check for errors: in normal use, they are impossible,
706                  * and in special cases, exiting is harmful. Example:
707                  * 'unshare --user' when user's shell is also from busybox.
708                  *
709                  * 'unshare --user' creates a new user namespace without any
710                  * uid mappings. Thus, busybox binary is setuid nobody:nogroup
711                  * within the namespace, as that is the only user. However,
712                  * since no uids are mapped, calls to setgid/setuid
713                  * fail (even though they would do nothing).
714                  */
715                 setgid(rgid);
716                 setuid(ruid);
717         }
718 #  if ENABLE_FEATURE_SUID_CONFIG
719  ret: ;
720         llist_free((llist_t*)suid_config, NULL);
721 #  endif
722 }
723 # else
724 #  define check_suid(x) ((void)0)
725 # endif /* FEATURE_SUID */
726
727
728 # if ENABLE_FEATURE_INSTALLER
729 static const char usr_bin [] ALIGN1 = "/usr/bin/";
730 static const char usr_sbin[] ALIGN1 = "/usr/sbin/";
731 static const char *const install_dir[] = {
732         &usr_bin [8], /* "/" */
733         &usr_bin [4], /* "/bin/" */
734         &usr_sbin[4]  /* "/sbin/" */
735 #  if !ENABLE_INSTALL_NO_USR
736         ,usr_bin
737         ,usr_sbin
738 #  endif
739 };
740
741 /* create (sym)links for each applet */
742 static void install_links(const char *busybox, int use_symbolic_links,
743                 char *custom_install_dir)
744 {
745         /* directory table
746          * this should be consistent w/ the enum,
747          * busybox.h::bb_install_loc_t, or else... */
748         int (*lf)(const char *, const char *);
749         char *fpc;
750         const char *appname = applet_names;
751         unsigned i;
752         int rc;
753
754         lf = link;
755         if (use_symbolic_links)
756                 lf = symlink;
757
758         for (i = 0; i < ARRAY_SIZE(applet_main); i++) {
759                 fpc = concat_path_file(
760                                 custom_install_dir ? custom_install_dir : install_dir[APPLET_INSTALL_LOC(i)],
761                                 appname);
762                 // debug: bb_error_msg("%slinking %s to busybox",
763                 //              use_symbolic_links ? "sym" : "", fpc);
764                 rc = lf(busybox, fpc);
765                 if (rc != 0 && errno != EEXIST) {
766                         bb_simple_perror_msg(fpc);
767                 }
768                 free(fpc);
769                 while (*appname++ != '\0')
770                         continue;
771         }
772 }
773 # elif ENABLE_BUSYBOX
774 static void install_links(const char *busybox UNUSED_PARAM,
775                 int use_symbolic_links UNUSED_PARAM,
776                 char *custom_install_dir UNUSED_PARAM)
777 {
778 }
779 # endif
780
781 static void run_applet_and_exit(const char *name, char **argv) NORETURN;
782
783 # if ENABLE_BUSYBOX
784 #  if ENABLE_FEATURE_SH_STANDALONE && ENABLE_FEATURE_TAB_COMPLETION
785     /*
786      * Insert "busybox" into applet table as well.
787      * This makes standalone shell tab-complete this name too.
788      * (Otherwise having "busybox" in applet table is not necessary,
789      * there is other code which routes "busyboxANY_SUFFIX" name
790      * to busybox_main()).
791      */
792 //usage:#define busybox_trivial_usage NOUSAGE_STR
793 //usage:#define busybox_full_usage ""
794 //applet:IF_BUSYBOX(IF_FEATURE_SH_STANDALONE(IF_FEATURE_TAB_COMPLETION(APPLET(busybox, BB_DIR_BIN, BB_SUID_MAYBE))))
795 int busybox_main(int argc, char *argv[]) MAIN_EXTERNALLY_VISIBLE;
796 #  else
797 #   define busybox_main(argc,argv) busybox_main(argv)
798 static
799 #  endif
800 int busybox_main(int argc UNUSED_PARAM, char **argv)
801 {
802         if (!argv[1]) {
803                 /* Called without arguments */
804                 const char *a;
805                 int col;
806                 unsigned output_width;
807  help:
808                 output_width = get_terminal_width(2);
809
810                 dup2(1, 2);
811                 full_write2_str(bb_banner); /* reuse const string */
812                 full_write2_str(" multi-call binary.\n"); /* reuse */
813                 full_write2_str(
814                         "BusyBox is copyrighted by many authors between 1998-2015.\n"
815                         "Licensed under GPLv2. See source distribution for detailed\n"
816                         "copyright notices.\n"
817                         "\n"
818                         "Usage: busybox [function [arguments]...]\n"
819                         "   or: busybox --list"IF_FEATURE_INSTALLER("[-full]")"\n"
820                         IF_FEATURE_INSTALLER(
821                         "   or: busybox --install [-s] [DIR]\n"
822                         )
823                         "   or: function [arguments]...\n"
824                         "\n"
825                         IF_NOT_FEATURE_SH_STANDALONE(
826                         "\tBusyBox is a multi-call binary that combines many common Unix\n"
827                         "\tutilities into a single executable.  Most people will create a\n"
828                         "\tlink to busybox for each function they wish to use and BusyBox\n"
829                         "\twill act like whatever it was invoked as.\n"
830                         )
831                         IF_FEATURE_SH_STANDALONE(
832                         "\tBusyBox is a multi-call binary that combines many common Unix\n"
833                         "\tutilities into a single executable.  The shell in this build\n"
834                         "\tis configured to run built-in utilities without $PATH search.\n"
835                         "\tYou don't need to install a link to busybox for each utility.\n"
836                         "\tTo run external program, use full path (/sbin/ip instead of ip).\n"
837                         )
838                         "\n"
839                         "Currently defined functions:\n"
840                 );
841                 col = 0;
842                 a = applet_names;
843                 /* prevent last comma to be in the very last pos */
844                 output_width--;
845                 while (*a) {
846                         int len2 = strlen(a) + 2;
847                         if (col >= (int)output_width - len2) {
848                                 full_write2_str(",\n");
849                                 col = 0;
850                         }
851                         if (col == 0) {
852                                 col = 6;
853                                 full_write2_str("\t");
854                         } else {
855                                 full_write2_str(", ");
856                         }
857                         full_write2_str(a);
858                         col += len2;
859                         a += len2 - 1;
860                 }
861                 full_write2_str("\n");
862                 return 0;
863         }
864
865         if (is_prefixed_with(argv[1], "--list")) {
866                 unsigned i = 0;
867                 const char *a = applet_names;
868                 dup2(1, 2);
869                 while (*a) {
870 #  if ENABLE_FEATURE_INSTALLER
871                         if (argv[1][6]) /* --list-full? */
872                                 full_write2_str(install_dir[APPLET_INSTALL_LOC(i)] + 1);
873 #  endif
874                         full_write2_str(a);
875                         full_write2_str("\n");
876                         i++;
877                         while (*a++ != '\0')
878                                 continue;
879                 }
880                 return 0;
881         }
882
883         if (ENABLE_FEATURE_INSTALLER && strcmp(argv[1], "--install") == 0) {
884                 int use_symbolic_links;
885                 const char *busybox;
886
887                 busybox = xmalloc_readlink(bb_busybox_exec_path);
888                 if (!busybox) {
889                         /* bb_busybox_exec_path is usually "/proc/self/exe".
890                          * In chroot, readlink("/proc/self/exe") usually fails.
891                          * In such case, better use argv[0] as symlink target
892                          * if it is a full path name.
893                          */
894                         if (argv[0][0] != '/')
895                                 bb_error_msg_and_die("'%s' is not an absolute path", argv[0]);
896                         busybox = argv[0];
897                 }
898                 /* busybox --install [-s] [DIR]:
899                  * -s: make symlinks
900                  * DIR: directory to install links to
901                  */
902                 use_symbolic_links = (argv[2] && strcmp(argv[2], "-s") == 0 && ++argv);
903                 install_links(busybox, use_symbolic_links, argv[2]);
904                 return 0;
905         }
906
907         if (strcmp(argv[1], "--help") == 0) {
908                 /* "busybox --help [<applet>]" */
909                 if (!argv[2])
910                         goto help;
911                 /* convert to "<applet> --help" */
912                 argv[0] = argv[2];
913                 argv[2] = NULL;
914         } else {
915                 /* "busybox <applet> arg1 arg2 ..." */
916                 argv++;
917         }
918         /* We support "busybox /a/path/to/applet args..." too. Allows for
919          * "#!/bin/busybox"-style wrappers */
920         applet_name = bb_get_last_path_component_nostrip(argv[0]);
921         run_applet_and_exit(applet_name, argv);
922 }
923 # endif
924
925 # if NUM_APPLETS > 0
926 void FAST_FUNC run_applet_no_and_exit(int applet_no, const char *name, char **argv)
927 {
928         int argc = string_array_len(argv);
929
930         /*
931          * We do not use argv[0]: do not want to repeat massaging of
932          * "-/sbin/halt" -> "halt", for example.
933          */
934         applet_name = name;
935
936         /* Special case. POSIX says "test --help"
937          * should be no different from e.g. "test --foo".
938          * Thus for "test", we skip --help check.
939          * "true" and "false" are also special.
940          */
941         if (1
942 #  if defined APPLET_NO_test
943          && applet_no != APPLET_NO_test
944 #  endif
945 #  if defined APPLET_NO_true
946          && applet_no != APPLET_NO_true
947 #  endif
948 #  if defined APPLET_NO_false
949          && applet_no != APPLET_NO_false
950 #  endif
951         ) {
952                 if (argc == 2 && strcmp(argv[1], "--help") == 0) {
953                         /* Make "foo --help" exit with 0: */
954                         xfunc_error_retval = 0;
955                         bb_show_usage();
956                 }
957         }
958         if (ENABLE_FEATURE_SUID)
959                 check_suid(applet_no);
960         xfunc_error_retval = applet_main[applet_no](argc, argv);
961         /* Note: applet_main() may also not return (die on a xfunc or such) */
962         xfunc_die();
963 }
964 # endif /* NUM_APPLETS > 0 */
965
966 # if NUM_SCRIPTS > 0
967 static char *
968 unpack_scripts(void)
969 {
970         char *outbuf = NULL;
971         bunzip_data *bd;
972         int i;
973         jmp_buf jmpbuf;
974
975         /* Setup for I/O error handling via longjmp */
976         i = setjmp(jmpbuf);
977         if (i == 0) {
978                 i = start_bunzip(&jmpbuf,
979                         &bd,
980                         /* src_fd: */ -1,
981                         /* inbuf:  */ packed_scripts,
982                         /* len:    */ sizeof(packed_scripts)
983                 );
984         }
985         /* read_bunzip can longjmp and end up here with i != 0
986          * on read data errors! Not trivial */
987         if (i == 0) {
988                 outbuf = xmalloc(UNPACKED_SCRIPTS_LENGTH);
989                 read_bunzip(bd, outbuf, UNPACKED_SCRIPTS_LENGTH);
990         }
991         dealloc_bunzip(bd);
992         return outbuf;
993 }
994
995 /*
996  * In standalone shell mode we sometimes want the index of the script
997  * and sometimes the index offset by NUM_APPLETS.
998  */
999 static int
1000 find_script_by_name(const char *arg)
1001 {
1002         const char *s = script_names;
1003         int i = 0;
1004
1005         while (*s) {
1006                 if (strcmp(arg, s) == 0)
1007                         return i;
1008                 i++;
1009                 while (*s++ != '\0')
1010                         continue;
1011         }
1012         return -1;
1013 }
1014
1015 char* FAST_FUNC
1016 get_script_content(unsigned n)
1017 {
1018         char *t = unpack_scripts();
1019         if (t) {
1020                 while (n != 0) {
1021                         while (*t++ != '\0')
1022                                 continue;
1023                         n--;
1024                 }
1025         }
1026         return t;
1027 }
1028 # endif /* NUM_SCRIPTS > 0 */
1029
1030 # if ENABLE_BUSYBOX || NUM_APPLETS > 0 || NUM_SCRIPTS > 0
1031 static NORETURN void run_applet_and_exit(const char *name, char **argv)
1032 {
1033 #  if ENABLE_BUSYBOX
1034         if (is_prefixed_with(name, "busybox"))
1035                 exit(busybox_main(/*unused:*/ 0, argv));
1036 #  endif
1037 #  if NUM_APPLETS > 0
1038         /* find_applet_by_name() search is more expensive, so goes second */
1039         {
1040                 int applet = find_applet_by_name(name);
1041                 if (applet >= 0)
1042                         run_applet_no_and_exit(applet, name, argv);
1043         }
1044 #  endif
1045 #  if NUM_SCRIPTS > 0
1046         {
1047                 int script = find_script_by_name(name);
1048                 if (script >= 0)
1049                         exit(ash_main(-script - 1, argv));
1050         }
1051 #  endif
1052
1053         /*bb_error_msg_and_die("applet not found"); - links in printf */
1054         full_write2_str(applet_name);
1055         full_write2_str(": applet not found\n");
1056         /* POSIX: "If a command is not found, the exit status shall be 127" */
1057         exit(127);
1058 }
1059 # endif
1060
1061 #endif /* !defined(SINGLE_APPLET_MAIN) */
1062
1063
1064 #if ENABLE_BUILD_LIBBUSYBOX
1065 int lbb_main(char **argv)
1066 #else
1067 int main(int argc UNUSED_PARAM, char **argv)
1068 #endif
1069 {
1070 #if 0
1071         /* TODO: find a use for a block of memory between end of .bss
1072          * and end of page. For example, I'm getting "_end:0x812e698 2408 bytes"
1073          * - more than 2k of wasted memory (in this particular build)
1074          * *per each running process*!
1075          * (If your linker does not generate "_end" name, weak attribute
1076          * makes &_end == NULL, end_len == 0 here.)
1077          */
1078         extern char _end[] __attribute__((weak));
1079         unsigned end_len = (-(int)_end) & 0xfff;
1080         printf("_end:%p %u bytes\n", &_end, end_len);
1081 #endif
1082
1083         /* Tweak malloc for reduced memory consumption */
1084 #ifdef M_TRIM_THRESHOLD
1085         /* M_TRIM_THRESHOLD is the maximum amount of freed top-most memory
1086          * to keep before releasing to the OS
1087          * Default is way too big: 256k
1088          */
1089         mallopt(M_TRIM_THRESHOLD, 8 * 1024);
1090 #endif
1091 #ifdef M_MMAP_THRESHOLD
1092         /* M_MMAP_THRESHOLD is the request size threshold for using mmap()
1093          * Default is too big: 256k
1094          */
1095         mallopt(M_MMAP_THRESHOLD, 32 * 1024 - 256);
1096 #endif
1097 #if 0 /*def M_TOP_PAD*/
1098         /* When the program break is increased, then M_TOP_PAD bytes are added
1099          * to the sbrk(2) request. When the heap is trimmed because of free(3),
1100          * this much free space is preserved at the top of the heap.
1101          * glibc default seems to be way too big: 128k, but need to verify.
1102          */
1103         mallopt(M_TOP_PAD, 8 * 1024);
1104 #endif
1105
1106 #if !BB_MMU
1107         /* NOMMU re-exec trick sets high-order bit in first byte of name */
1108         if (argv[0][0] & 0x80) {
1109                 re_execed = 1;
1110                 argv[0][0] &= 0x7f;
1111         }
1112 #endif
1113
1114 #if defined(SINGLE_APPLET_MAIN)
1115
1116         /* Only one applet is selected in .config */
1117         if (argv[1] && is_prefixed_with(argv[0], "busybox")) {
1118                 /* "busybox <applet> <params>" should still work as expected */
1119                 argv++;
1120         }
1121         /* applet_names in this case is just "applet\0\0" */
1122         lbb_prepare(applet_names IF_FEATURE_INDIVIDUAL(, argv));
1123 # if ENABLE_BUILD_LIBBUSYBOX
1124         return SINGLE_APPLET_MAIN(string_array_len(argv), argv);
1125 # else
1126         return SINGLE_APPLET_MAIN(argc, argv);
1127 # endif
1128
1129 #elif !ENABLE_BUSYBOX && NUM_APPLETS == 0
1130
1131         full_write2_str(bb_basename(argv[0]));
1132         full_write2_str(": no applets enabled\n");
1133         exit(127);
1134
1135 #else
1136
1137         lbb_prepare("busybox" IF_FEATURE_INDIVIDUAL(, argv));
1138 # if !ENABLE_BUSYBOX
1139         if (argv[1] && is_prefixed_with(bb_basename(argv[0]), "busybox"))
1140                 argv++;
1141 # endif
1142         applet_name = argv[0];
1143         if (applet_name[0] == '-')
1144                 applet_name++;
1145         applet_name = bb_basename(applet_name);
1146
1147         /* If we are a result of execv("/proc/self/exe"), fix ugly comm of "exe" */
1148         if (ENABLE_FEATURE_SH_STANDALONE
1149          || ENABLE_FEATURE_PREFER_APPLETS
1150          || !BB_MMU
1151         ) {
1152                 if (NUM_APPLETS > 1)
1153                         set_task_comm(applet_name);
1154         }
1155
1156         parse_config_file(); /* ...maybe, if FEATURE_SUID_CONFIG */
1157         run_applet_and_exit(applet_name, argv);
1158
1159 #endif
1160 }