kill superfluous returns at the end of void functions
[oweals/busybox.git] / applets / applets.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 #define PROTOTYPES
19 #include "applets.h"
20 #undef PROTOTYPES
21
22
23 /* Apparently uclibc defines __GLIBC__ (compat trick?). Oh well. */
24 #if ENABLE_STATIC && defined(__GLIBC__) && !defined(__UCLIBC__)
25 #warning Static linking against glibc produces buggy executables
26 #warning (glibc does not cope well with ld --gc-sections).
27 #warning See sources.redhat.com/bugzilla/show_bug.cgi?id=3400
28 #warning Note that glibc is unsuitable for static linking anyway.
29 #warning If you still want to do it, remove -Wl,--gc-sections
30 #warning from top-level Makefile and remove this warning.
31 #endif
32
33 #if ENABLE_SHOW_USAGE && !ENABLE_FEATURE_COMPRESS_USAGE
34 static const char usage_messages[] =
35 #define MAKE_USAGE
36 #include "usage.h"
37 #include "applets.h"
38 ;
39 #undef MAKE_USAGE
40 #else
41 #define usage_messages 0
42 #endif /* ENABLE_SHOW_USAGE */
43
44 #undef APPLET
45 #undef APPLET_NOUSAGE
46 #undef PROTOTYPES
47 #include "applets.h"
48
49 static struct BB_applet *applet_using;
50
51 /* The -1 arises because of the {0,NULL,0,-1} entry above. */
52 const unsigned short NUM_APPLETS = (sizeof (applets) / sizeof (struct BB_applet) - 1);
53
54
55 #ifdef CONFIG_FEATURE_SUID_CONFIG
56
57 #include <ctype.h>
58
59 #define CONFIG_FILE "/etc/busybox.conf"
60
61 /* applets [] is const, so we have to define this "override" structure */
62 static struct BB_suid_config
63 {
64         struct BB_applet *m_applet;
65
66         uid_t m_uid;
67         gid_t m_gid;
68         mode_t m_mode;
69
70         struct BB_suid_config *m_next;
71 } *suid_config;
72
73 static int suid_cfg_readable;
74
75 /* check if u is member of group g */
76 static int ingroup(uid_t u, gid_t g)
77 {
78         struct group *grp = getgrgid(g);
79
80         if (grp) {
81                 char **mem;
82
83                 for (mem = grp->gr_mem; *mem; mem++) {
84                         struct passwd *pwd = getpwnam(*mem);
85
86                         if (pwd && (pwd->pw_uid == u))
87                                 return 1;
88                 }
89         }
90         return 0;
91 }
92
93 /* This should probably be a libbb routine.  In that case,
94  * I'd probably rename it to something like bb_trimmed_slice.
95  */
96 static char *get_trimmed_slice(char *s, char *e)
97 {
98         /* First, consider the value at e to be nul and back up until we
99          * reach a non-space char.  Set the char after that (possibly at
100          * the original e) to nul. */
101         while (e-- > s) {
102                 if (!isspace(*e)) {
103                         break;
104                 }
105         }
106         e[1] = 0;
107
108         /* Next, advance past all leading space and return a ptr to the
109          * first non-space char; possibly the terminating nul. */
110         return skip_whitespace(s);
111 }
112
113
114 #define parse_error(x)  do { errmsg = x; goto pe_label; } while(0)
115
116 /* Don't depend on the tools to combine strings. */
117 static const char config_file[] = CONFIG_FILE;
118
119 /* There are 4 chars + 1 nul for each of user/group/other. */
120 static const char mode_chars[] = "Ssx-\0Ssx-\0Ttx-";
121
122 /* We don't supply a value for the nul, so an index adjustment is
123  * necessary below.  Also, we use unsigned short here to save some
124  * space even though these are really mode_t values. */
125 static const unsigned short mode_mask[] = {
126         /*  SST         sst                 xxx   --- */
127         S_ISUID,    S_ISUID|S_IXUSR,    S_IXUSR,    0,  /* user */
128         S_ISGID,    S_ISGID|S_IXGRP,    S_IXGRP,    0,  /* group */
129         0,          S_IXOTH,            S_IXOTH,    0   /* other */
130 };
131
132 static void parse_config_file(void)
133 {
134         struct BB_suid_config *sct_head;
135         struct BB_suid_config *sct;
136         struct BB_applet *applet;
137         FILE *f;
138         const char *errmsg;
139         char *s;
140         char *e;
141         int i, lc, section;
142         char buffer[256];
143         struct stat st;
144
145         assert(!suid_config);           /* Should be set to NULL by bss init. */
146
147         if ((stat(config_file, &st) != 0)                       /* No config file? */
148                 || !S_ISREG(st.st_mode)                                 /* Not a regular file? */
149                 || (st.st_uid != 0)                                             /* Not owned by root? */
150                 || (st.st_mode & (S_IWGRP | S_IWOTH))   /* Writable by non-root? */
151                 || !(f = fopen(config_file, "r"))               /* Cannot open? */
152                 ) {
153                 return;
154         }
155
156         suid_cfg_readable = 1;
157         sct_head = NULL;
158         section = lc = 0;
159
160         do {
161                 s = buffer;
162
163                 if (!fgets(s, sizeof(buffer), f)) { /* Are we done? */
164                         if (ferror(f)) {   /* Make sure it wasn't a read error. */
165                                 parse_error("reading");
166                         }
167                         fclose(f);
168                         suid_config = sct_head; /* Success, so set the pointer. */
169                         return;
170                 }
171
172                 lc++;                                   /* Got a (partial) line. */
173
174                 /* If a line is too long for our buffer, we consider it an error.
175                  * The following test does mistreat one corner case though.
176                  * If the final line of the file does not end with a newline and
177                  * yet exactly fills the buffer, it will be treated as too long
178                  * even though there isn't really a problem.  But it isn't really
179                  * worth adding code to deal with such an unlikely situation, and
180                  * we do err on the side of caution.  Besides, the line would be
181                  * too long if it did end with a newline. */
182                 if (!strchr(s, '\n') && !feof(f)) {
183                         parse_error("line too long");
184                 }
185
186                 /* Trim leading and trailing whitespace, ignoring comments, and
187                  * check if the resulting string is empty. */
188                 if (!*(s = get_trimmed_slice(s, strchrnul(s, '#')))) {
189                         continue;
190                 }
191
192                 /* Check for a section header. */
193
194                 if (*s == '[') {
195                         /* Unlike the old code, we ignore leading and trailing
196                          * whitespace for the section name.  We also require that
197                          * there are no stray characters after the closing bracket. */
198                         if (!(e = strchr(s, ']'))       /* Missing right bracket? */
199                                 || e[1]                                 /* Trailing characters? */
200                                 || !*(s = get_trimmed_slice(s+1, e)) /* Missing name? */
201                                 ) {
202                                 parse_error("section header");
203                         }
204                         /* Right now we only have one section so just check it.
205                          * If more sections are added in the future, please don't
206                          * resort to cascading ifs with multiple strcasecmp calls.
207                          * That kind of bloated code is all too common.  A loop
208                          * and a string table would be a better choice unless the
209                          * number of sections is very small. */
210                         if (strcasecmp(s, "SUID") == 0) {
211                                 section = 1;
212                                 continue;
213                         }
214                         section = -1;   /* Unknown section so set to skip. */
215                         continue;
216                 }
217
218                 /* Process sections. */
219
220                 if (section == 1) {             /* SUID */
221                         /* Since we trimmed leading and trailing space above, we're
222                          * now looking for strings of the form
223                          *    <key>[::space::]*=[::space::]*<value>
224                          * where both key and value could contain inner whitespace. */
225
226                         /* First get the key (an applet name in our case). */
227                         if (!!(e = strchr(s, '='))) {
228                                 s = get_trimmed_slice(s, e);
229                         }
230                         if (!e || !*s) {        /* Missing '=' or empty key. */
231                                 parse_error("keyword");
232                         }
233
234                         /* Ok, we have an applet name.  Process the rhs if this
235                          * applet is currently built in and ignore it otherwise.
236                          * Note: This can hide config file bugs which only pop
237                          * up when the busybox configuration is changed. */
238                         if ((applet = find_applet_by_name(s))) {
239                                 /* Note: We currently don't check for duplicates!
240                                  * The last config line for each applet will be the
241                                  * one used since we insert at the head of the list.
242                                  * I suppose this could be considered a feature. */
243                                 sct = xmalloc(sizeof(struct BB_suid_config));
244                                 sct->m_applet = applet;
245                                 sct->m_mode = 0;
246                                 sct->m_next = sct_head;
247                                 sct_head = sct;
248
249                                 /* Get the specified mode. */
250
251                                 e = skip_whitespace(e+1);
252
253                                 for (i=0 ; i < 3 ; i++) {
254                                         const char *q;
255                                         if (!*(q = strchrnul(mode_chars + 5*i, *e++))) {
256                                                 parse_error("mode");
257                                         }
258                                         /* Adjust by -i to account for nul. */
259                                         sct->m_mode |= mode_mask[(q - mode_chars) - i];
260                                 }
261
262                                 /* Now get the the user/group info. */
263
264                                 s = skip_whitespace(e);
265
266                                 /* Note: We require whitespace between the mode and the
267                                  * user/group info. */
268                                 if ((s == e) || !(e = strchr(s, '.'))) {
269                                         parse_error("<uid>.<gid>");
270                                 }
271                                 *e++ = 0;
272
273                                 /* We can't use get_ug_id here since it would exit()
274                                  * if a uid or gid was not found.  Oh well... */
275                                 {
276                                         char *e2;
277
278                                         sct->m_uid = strtoul(s, &e2, 10);
279                                         if (*e2 || (s == e2)) {
280                                                 struct passwd *pwd = getpwnam(s);
281                                                 if (!pwd) {
282                                                         parse_error("user");
283                                                 }
284                                                 sct->m_uid = pwd->pw_uid;
285                                         }
286
287                                         sct->m_gid = strtoul(e, &e2, 10);
288                                         if (*e2 || (e == e2)) {
289                                                 struct group *grp;
290                                                 if (!(grp = getgrnam(e))) {
291                                                         parse_error("group");
292                                                 }
293                                                 sct->m_gid = grp->gr_gid;
294                                         }
295                                 }
296                         }
297                         continue;
298                 }
299
300                 /* Unknown sections are ignored. */
301
302                 /* Encountering configuration lines prior to seeing a
303                  * section header is treated as an error.  This is how
304                  * the old code worked, but it may not be desirable.
305                  * We may want to simply ignore such lines in case they
306                  * are used in some future version of busybox. */
307                 if (!section) {
308                         parse_error("keyword outside section");
309                 }
310
311         } while (1);
312
313  pe_label:
314         fprintf(stderr, "Parse error in %s, line %d: %s\n",
315                         config_file, lc, errmsg);
316
317         fclose(f);
318         /* Release any allocated memory before returning. */
319         while (sct_head) {
320                 sct = sct_head->m_next;
321                 free(sct_head);
322                 sct_head = sct;
323         }
324 }
325
326 #else
327 #define parse_config_file() ((void)0)
328 #endif /* CONFIG_FEATURE_SUID_CONFIG */
329
330 #ifdef CONFIG_FEATURE_SUID
331 static void check_suid(struct BB_applet *applet)
332 {
333         uid_t ruid = getuid();               /* real [ug]id */
334         uid_t rgid = getgid();
335
336 #ifdef CONFIG_FEATURE_SUID_CONFIG
337         if (suid_cfg_readable) {
338                 struct BB_suid_config *sct;
339
340                 for (sct = suid_config; sct; sct = sct->m_next) {
341                         if (sct->m_applet == applet)
342                                 break;
343                 }
344                 if (sct) {
345                         mode_t m = sct->m_mode;
346
347                         if (sct->m_uid == ruid)
348                                 /* same uid */
349                                 m >>= 6;
350                         else if ((sct->m_gid == rgid) || ingroup(ruid, sct->m_gid))
351                                 /* same group / in group */
352                                 m >>= 3;
353
354                         if (!(m & S_IXOTH))           /* is x bit not set ? */
355                                 bb_error_msg_and_die("you have no permission to run this applet!");
356
357                         if (sct->m_gid != 0) {
358                                 /* _both_ have to be set for sgid */
359                                 if ((sct->m_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
360                                         xsetgid(sct->m_gid);
361                                 } else xsetgid(rgid); /* no sgid -> drop */
362                         }
363                         if (sct->m_uid != 0) {
364                                 if (sct->m_mode & S_ISUID) xsetuid(sct->m_uid);
365                                 else xsetuid(ruid); /* no suid -> drop */
366                         }
367                 } else {
368                         /* default: drop all privileges */
369                         xsetgid(rgid);
370                         xsetuid(ruid);
371                 }
372                 return;
373         } else {
374 #ifndef CONFIG_FEATURE_SUID_CONFIG_QUIET
375                 static int onetime = 0;
376
377                 if (!onetime) {
378                         onetime = 1;
379                         fprintf(stderr, "Using fallback suid method\n");
380                 }
381 #endif
382         }
383 #endif
384
385         if (applet->need_suid == _BB_SUID_ALWAYS) {
386                 if (geteuid()) bb_error_msg_and_die("applet requires root privileges!");
387         } else if (applet->need_suid == _BB_SUID_NEVER) {
388                 xsetgid(rgid);                          /* drop all privileges */
389                 xsetuid(ruid);
390         }
391 }
392 #else
393 #define check_suid(x)
394 #endif /* CONFIG_FEATURE_SUID */
395
396
397
398 #ifdef CONFIG_FEATURE_COMPRESS_USAGE
399
400 #include "usage_compressed.h"
401 #include "unarchive.h"
402
403 static const char *unpack_usage_messages(void)
404 {
405         int input[2], output[2], pid;
406         char *buf;
407
408         if(pipe(input) < 0 || pipe(output) < 0)
409                 exit(1);
410
411         pid = fork();
412         switch (pid) {
413         case -1: /* error */
414                 exit(1);
415         case 0: /* child */
416                 close(input[1]);
417                 close(output[0]);
418                 uncompressStream(input[0], output[1]);
419                 exit(0);
420         }
421         /* parent */
422
423         close(input[0]);
424         close(output[1]);
425         pid = fork();
426         switch (pid) {
427         case -1: /* error */
428                 exit(1);
429         case 0: /* child */
430                 full_write(input[1], packed_usage, sizeof(packed_usage));
431                 exit(0);
432         }
433         /* parent */
434         close(input[1]);
435
436         buf = xmalloc(SIZEOF_usage_messages);
437         full_read(output[0], buf, SIZEOF_usage_messages);
438         return buf;
439 }
440
441 #else
442 #define unpack_usage_messages() usage_messages
443 #endif /* ENABLE_FEATURE_COMPRESS_USAGE */
444
445 void bb_show_usage(void)
446 {
447         if (ENABLE_SHOW_USAGE) {
448                 const char *format_string;
449                 const char *usage_string = unpack_usage_messages();
450                 int i;
451
452                 for (i = applet_using - applets; i > 0;)
453                         if (!*usage_string++) --i;
454
455                 format_string = "%s\n\nUsage: %s %s\n\n";
456                 if (*usage_string == '\b')
457                         format_string = "%s\n\nNo help available.\n\n";
458                 fprintf(stderr, format_string, bb_msg_full_version,
459                         applet_using->name, usage_string);
460         }
461
462         exit(xfunc_error_retval);
463 }
464
465 static int applet_name_compare(const void *name, const void *vapplet)
466 {
467         const struct BB_applet *applet = vapplet;
468
469         return strcmp(name, applet->name);
470 }
471
472 struct BB_applet *find_applet_by_name(const char *name)
473 {
474         return bsearch(name, applets, NUM_APPLETS, sizeof(struct BB_applet),
475                                 applet_name_compare);
476 }
477
478 void run_applet_by_name(const char *name, int argc, char **argv)
479 {
480         if (ENABLE_FEATURE_SUID_CONFIG)
481                 parse_config_file();
482
483         if (!strncmp(name, "busybox", 7))
484                 exit(busybox_main(argc, argv));
485         /* Do a binary search to find the applet entry given the name. */
486         applet_using = find_applet_by_name(name);
487         if (applet_using) {
488                 applet_name = applet_using->name;
489                 if (argc == 2 && !strcmp(argv[1], "--help"))
490                         bb_show_usage();
491                 if (ENABLE_FEATURE_SUID)
492                         check_suid(applet_using);
493                 exit(applet_using->main(argc, argv));
494         }
495 }