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