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