xref: /aosp_15_r20/external/toybox/main.c (revision cf5a6c84e2b8763fc1a7db14496fd4742913b199)
1 /* Toybox infrastructure.
2  *
3  * Copyright 2006 Rob Landley <[email protected]>
4  */
5 
6 #include "toys.h"
7 
8 // Populate toy_list[].
9 
10 #undef NEWTOY
11 #undef OLDTOY
12 #define NEWTOY(name, opts, flags) {#name, name##_main, OPTSTR_##name, flags},
13 #define OLDTOY(name, oldname, flags) \
14   {#name, oldname##_main, OPTSTR_##oldname, flags},
15 
16 struct toy_list toy_list[] = {
17 #include "generated/newtoys.h"
18 };
19 
20 // global context for this command.
21 
22 struct toy_context toys;
23 union global_union this;
24 char *toybox_version = TOYBOX_VERSION, toybuf[4096], libbuf[4096];
25 
toy_find(char * name)26 struct toy_list *toy_find(char *name)
27 {
28   int top, bottom, middle;
29 
30   if (!CFG_TOYBOX || strchr(name, '/')) return 0;
31 
32   // Multiplexer name works as prefix, else skip first entry (it's out of order)
33   if (!toys.which && strstart(&name, toy_list->name)) return toy_list;
34   bottom = 1;
35 
36   // Binary search to find this command.
37   top = ARRAY_LEN(toy_list)-1;
38   for (;;) {
39     int result;
40 
41     middle = (top+bottom)/2;
42     if (middle<bottom || middle>top) return 0;
43     result = strcmp(name,toy_list[middle].name);
44     if (!result) return toy_list+middle;
45     if (result<0) top = --middle;
46     else bottom = ++middle;
47   }
48 }
49 
50 // Figure out whether or not anything is using the option parsing logic,
51 // because the compiler can't figure out whether or not to optimize it away
52 // on its' own.  NEED_OPTIONS becomes a constant allowing if() to optimize
53 // stuff out via dead code elimination.
54 
55 #undef NEWTOY
56 #undef OLDTOY
57 #define NEWTOY(name, opts, flags) opts ||
58 #define OLDTOY(name, oldname, flags) OPTSTR_##oldname ||
59 static const int NEED_OPTIONS =
60 #include "generated/newtoys.h"
61 0;  // Ends the opts || opts || opts...
62 
63 // Populate help text array
64 
65 #undef NEWTOY
66 #undef OLDTOY
67 #define NEWTOY(name,opt,flags) HELP_##name "\0"
68 #if CFG_TOYBOX
69 #define OLDTOY(name,oldname,flags) "\xff" #oldname "\0"
70 #else
71 #define OLDTOY(name, oldname, flags) HELP_##oldname "\0"
72 #endif
73 
74 #include "generated/help.h"
75 static const char help_data[] =
76 #include "generated/newtoys.h"
77 ;
78 
79 #if CFG_TOYBOX_ZHELP
80 #include "generated/zhelp.h"
81 #else
82 static char *zhelp_data = 0;
83 #define ZHELP_LEN 0
84 #endif
85 
show_help(FILE * out,int flags)86 void show_help(FILE *out, int flags)
87 {
88   int i = toys.which-toy_list;
89   char *s, *ss, *hd;
90 
91   if (!CFG_TOYBOX_HELP) return;
92 
93   if (CFG_TOYBOX_ZHELP)
94     gunzip_mem(zhelp_data, sizeof(zhelp_data), hd = xmalloc(ZHELP_LEN),
95       ZHELP_LEN);
96   else hd = (void *)help_data;
97 
98   if (flags & HELP_HEADER)
99     fprintf(out, "Toybox %s"USE_TOYBOX(" multicall binary")"%s\n\n",
100       toybox_version, (CFG_TOYBOX && i) ? " (see toybox --help)"
101       : " (see https://landley.net/toybox)");
102 
103   for (;;) {
104     s = (void *)help_data;
105     while (i--) s += strlen(s) + 1;
106     // If it's an alias, restart search for real name
107     if (*s != 255) break;
108     i = toy_find(++s)-toy_list;
109     if ((flags & HELP_SEE) && toy_list[i].flags) {
110       if (flags & HELP_HTML) fprintf(out, "See <a href=#%s>%s</a>\n", s, s);
111       else fprintf(out, "%s see %s\n", toys.which->name, s);
112 
113       return;
114     }
115   }
116 
117   if (!(flags & HELP_USAGE)) fprintf(out, "%s\n", s);
118   else {
119     strstart(&s, "usage: ");
120     for (ss = s; *ss && *ss!='\n'; ss++);
121     fprintf(out, "%.*s\n", (int)(ss-s), s);
122   }
123 }
124 
unknown(char * name)125 static void unknown(char *name)
126 {
127   toys.exitval = 127;
128   toys.which = toy_list;
129   help_exit("Unknown command %s", name);
130 }
131 
132 // Parse --help and --version for (almost) all commands
check_help(char ** arg)133 void check_help(char **arg)
134 {
135   long flags = toys.which->flags;
136 
137   if (!CFG_TOYBOX_HELP_DASHDASH || !*arg) return;
138   if (!CFG_TOYBOX || toys.which!=toy_list) if (flags&TOYFLAG_NOHELP) return;
139 
140   if (!strcmp(*arg, "--help")) {
141     if (CFG_TOYBOX && toys.which == toy_list && arg[1]) {
142       toys.which = 0;
143       if (!(toys.which = toy_find(arg[1]))) unknown(arg[1]);
144     }
145     show_help(stdout, HELP_HEADER);
146     xexit();
147   }
148 
149   if (!strcmp(*arg, "--version")) {
150     // Lie to autoconf when it asks stupid questions, so configure regexes
151     // that look for "GNU sed version %f" greater than some old buggy number
152     // don't fail us for not matching their narrow expectations.
153     *toybuf = 0;
154     if (flags&TOYFLAG_AUTOCONF)
155       sprintf(toybuf, " (is not GNU %s 9.0)", toys.which->name);
156     xprintf("toybox %s%s\n", toybox_version, toybuf);
157     xexit();
158   }
159 }
160 
161 // Setup toybox global state for this command.
toy_singleinit(struct toy_list * which,char * argv[])162 void toy_singleinit(struct toy_list *which, char *argv[])
163 {
164   toys.which = which;
165   toys.argv = argv;
166   toys.toycount = ARRAY_LEN(toy_list);
167 
168   if (NEED_OPTIONS && which->options) get_optflags();
169   else {
170     check_help(toys.optargs = argv+1);
171     for (toys.optc = 0; toys.optargs[toys.optc]; toys.optc++);
172   }
173 
174   // Setup we only want to do once: skip for multiplexer or NOFORK reentry
175   if (!(CFG_TOYBOX && which == toy_list) && !(which->flags & TOYFLAG_NOFORK)) {
176     char *buf = 0;
177     int btype = _IOFBF;
178 
179     toys.old_umask = umask(0);
180     if (!(which->flags & TOYFLAG_UMASK)) umask(toys.old_umask);
181 
182     // Try user's locale, but if that isn't UTF-8 merge in a UTF-8 locale's
183     // character type data. (Fall back to en_US for MacOS.)
184     setlocale(LC_CTYPE, "");
185     if (strcmp("UTF-8", nl_langinfo(CODESET)))
186       uselocale(newlocale(LC_CTYPE_MASK, "C.UTF-8", 0) ? :
187         newlocale(LC_CTYPE_MASK, "en_US.UTF-8", 0));
188 
189     if (which->flags & TOYFLAG_LINEBUF) btype = _IOLBF;
190     else if (which->flags & TOYFLAG_NOBUF) btype = _IONBF;
191     else buf = xmalloc(4096);
192     setvbuf(stdout, buf, btype, buf ? 4096 : 0);
193   }
194 }
195 
196 // Full init needed by multiplexer or reentrant calls, calls singleinit at end
toy_init(struct toy_list * which,char * argv[])197 void toy_init(struct toy_list *which, char *argv[])
198 {
199   void *oldwhich = toys.which;
200 
201   // Drop permissions for non-suid commands.
202   if (CFG_TOYBOX_SUID) {
203     if (!toys.which) toys.which = toy_list;
204 
205     uid_t uid = getuid(), euid = geteuid();
206 
207     if (!(which->flags & TOYFLAG_STAYROOT)) {
208       if (uid != euid) {
209         if (setuid(uid)) perror_exit("setuid %d->%d", euid, uid); // drop root
210         euid = uid;
211         toys.wasroot++;
212       }
213     } else if (CFG_TOYBOX_DEBUG && uid && which != toy_list)
214       error_msg("Not installed suid root");
215 
216     if ((which->flags & TOYFLAG_NEEDROOT) && euid) {
217       toys.which = which;
218       check_help(argv+1);
219       help_exit("Not root");
220     }
221   }
222 
223   memset(&toys, 0, offsetof(struct toy_context, rebound));
224   if (oldwhich) memset(&this, 0, sizeof(this));
225 
226   // Continue to portion of init needed by standalone commands
227   toy_singleinit(which, argv);
228 }
229 
230 // Run an internal toybox command.
231 // Only returns if it can't run command internally, otherwise xexit() when done.
toy_exec_which(struct toy_list * which,char * argv[])232 void toy_exec_which(struct toy_list *which, char *argv[])
233 {
234   // Return if we can't find it (which includes no multiplexer case),
235   if (!which || (which->flags&TOYFLAG_NOFORK)) return;
236 
237   // Return if stack depth getting noticeable (proxy for leaked heap, etc).
238 
239   // Compiler writers have decided subtracting char * is undefined behavior,
240   // so convert to integers. (LP64 says sizeof(long)==sizeof(pointer).)
241   // Signed typecast so stack growth direction is irrelevant: we're measuring
242   // the distance between two pointers on the same stack, hence the labs().
243   if (!CFG_TOYBOX_NORECURSE && toys.stacktop)
244     if (labs((long)toys.stacktop-(long)&which)>24000) return;
245 
246   // Return if we need to re-exec to acquire root via suid bit.
247   if (toys.which && (which->flags&TOYFLAG_ROOTONLY) && toys.wasroot) return;
248 
249   // Run command
250   toy_init(which, argv);
251   if (toys.which) toys.which->toy_main();
252   xexit();
253 }
254 
255 // Lookup internal toybox command to run via argv[0]
toy_exec(char * argv[])256 void toy_exec(char *argv[])
257 {
258   toy_exec_which(toy_find(*argv), argv);
259 }
260 
261 // Multiplexer command, first argument is command to run, rest are args to that.
262 // If first argument starts with - output list of command install paths.
toybox_main(void)263 void toybox_main(void)
264 {
265   char *toy_paths[] = {"usr/", "bin/", "sbin/", 0}, *s = toys.argv[1];
266   int i, len = 0;
267   unsigned width = 80;
268 
269   // fast path: try to exec immediately.
270   // (Leave toys.which null to disable suid return logic.)
271   // Try dereferencing symlinks until we hit a recognized name
272   while (s) {
273     char *ss = basename(s);
274     struct toy_list *tl = toy_find(ss);
275 
276     if (tl==toy_list && s!=toys.argv[1]) unknown(ss);
277     toy_exec_which(tl, toys.argv+1);
278     s = (0<readlink(s, libbuf, sizeof(libbuf))) ? libbuf : 0;
279   }
280 
281   // For early error reporting
282   toys.which = toy_list;
283 
284   if (toys.argv[1] && strcmp(toys.argv[1], "--long")) unknown(toys.argv[1]);
285 
286   // Output list of commands.
287   terminal_size(&width, 0);
288   for (i = 1; i<ARRAY_LEN(toy_list); i++) {
289     int fl = toy_list[i].flags;
290     if (fl & TOYMASK_LOCATION) {
291       if (toys.argv[1]) {
292         int j;
293         for (j = 0; toy_paths[j]; j++)
294           if (fl & (1<<j)) len += printf("%s", toy_paths[j]);
295       }
296       len += printf("%s",toy_list[i].name);
297       if (++len > width-15) len = 0;
298       xputc(len ? ' ' : '\n');
299     }
300   }
301   xputc('\n');
302 }
303 
main(int argc,char * argv[])304 int main(int argc, char *argv[])
305 {
306   // don't segfault if our environment is crazy
307   // TODO mooted by kernel commit dcd46d897adb7 5.17 kernel Jan 2022
308   if (!*argv) return 127;
309 
310   // Snapshot stack location so we can detect recursion depth later.
311   // Nommu has special reentry path, !stacktop = "vfork/exec self happened"
312   if (!CFG_TOYBOX_FORK && (0x80 & **argv)) **argv &= 0x7f;
313   else {
314     int stack_start;  // here so probe var won't permanently eat stack
315 
316     toys.stacktop = &stack_start;
317   }
318 
319   // Android before O had non-default SIGPIPE, 7 years = remove in Sep 2024.
320   if (CFG_TOYBOX_ON_ANDROID) signal(SIGPIPE, SIG_DFL);
321 
322   if (CFG_TOYBOX) {
323     // Call the multiplexer with argv[] as its arguments so it can toy_find()
324     toys.argv = argv-1;
325     toybox_main();
326   } else {
327     // single command built standalone with no multiplexer is first list entry
328     toy_singleinit(toy_list, argv);
329     toy_list->toy_main();
330   }
331 
332   xexit();
333 }
334