• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Toybox infrastructure.
2  *
3  * Copyright 2006 Rob Landley <rob@landley.net>
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 char *help_data =
76 #include "generated/newtoys.h"
77 ;
78 
show_help(FILE * out,int flags)79 void show_help(FILE *out, int flags)
80 {
81   int i = toys.which-toy_list;
82   char *s, *ss;
83 
84   if (CFG_TOYBOX_HELP) {
85     if (flags & HELP_HEADER)
86       fprintf(out, "Toybox %s"USE_TOYBOX(" multicall binary")"%s\n\n",
87         toybox_version, (CFG_TOYBOX && i) ? " (see toybox --help)"
88         : " (see https://landley.net/toybox)");
89 
90     for (;;) {
91       s = help_data;
92       while (i--) s += strlen(s) + 1;
93       // If it's an alias, restart search for real name
94       if (*s != 255) break;
95       i = toy_find(++s)-toy_list;
96       if ((flags & HELP_SEE) && toy_list[i].flags) {
97         if (flags & HELP_HTML) fprintf(out, "See <a href=#%s>%s</a>\n", s, s);
98         else fprintf(out, "%s see %s\n", toys.which->name, s);
99 
100         return;
101       }
102     }
103 
104     if (!(flags & HELP_USAGE)) fprintf(out, "%s\n", s);
105     else {
106       strstart(&s, "usage: ");
107       for (ss = s; *ss && *ss!='\n'; ss++);
108       fprintf(out, "%.*s\n", (int)(ss-s), s);
109     }
110   }
111 }
112 
unknown(char * name)113 static void unknown(char *name)
114 {
115   toys.exitval = 127;
116   toys.which = toy_list;
117   help_exit("Unknown command %s", name);
118 }
119 
120 // Parse --help and --version for (almost) all commands
check_help(char ** arg)121 void check_help(char **arg)
122 {
123   if (!CFG_TOYBOX_HELP_DASHDASH || !*arg) return;
124   if (!CFG_TOYBOX || toys.which != toy_list)
125     if (toys.which->flags&TOYFLAG_NOHELP) return;
126 
127   if (!strcmp(*arg, "--help")) {
128     if (CFG_TOYBOX && toys.which == toy_list && arg[1]) {
129       toys.which = 0;
130       if (!(toys.which = toy_find(arg[1]))) unknown(arg[1]);
131     }
132     show_help(stdout, HELP_HEADER);
133     xexit();
134   }
135 
136   if (!strcmp(*arg, "--version")) {
137     xprintf("toybox %s\n", toybox_version);
138     xexit();
139   }
140 }
141 
142 // Setup toybox global state for this command.
toy_singleinit(struct toy_list * which,char * argv[])143 void toy_singleinit(struct toy_list *which, char *argv[])
144 {
145   toys.which = which;
146   toys.argv = argv;
147   toys.toycount = ARRAY_LEN(toy_list);
148 
149   if (NEED_OPTIONS && which->options) get_optflags();
150   else {
151     check_help(toys.optargs = argv+1);
152     for (toys.optc = 0; toys.optargs[toys.optc]; toys.optc++);
153   }
154 
155   // Setup we only want to do once: skip for multiplexer or NOFORK reentry
156   if (!(CFG_TOYBOX && which == toy_list) && !(which->flags & TOYFLAG_NOFORK)) {
157     toys.old_umask = umask(0);
158     if (!(which->flags & TOYFLAG_UMASK)) umask(toys.old_umask);
159 
160     // Try user's locale, but if that isn't UTF-8 merge in a UTF-8 locale's
161     // character type data. (Fall back to en_US for MacOS.)
162     setlocale(LC_CTYPE, "");
163     if (strcmp("UTF-8", nl_langinfo(CODESET)))
164       uselocale(newlocale(LC_CTYPE_MASK, "C.UTF-8", 0) ? :
165         newlocale(LC_CTYPE_MASK, "en_US.UTF-8", 0));
166 
167     setvbuf(stdout, 0, (which->flags & TOYFLAG_LINEBUF) ? _IOLBF : _IONBF, 0);
168   }
169 }
170 
171 // Full init needed by multiplexer or reentrant calls, calls singleinit at end
toy_init(struct toy_list * which,char * argv[])172 void toy_init(struct toy_list *which, char *argv[])
173 {
174   void *oldwhich = toys.which;
175 
176   // Drop permissions for non-suid commands.
177   if (CFG_TOYBOX_SUID) {
178     if (!toys.which) toys.which = toy_list;
179 
180     uid_t uid = getuid(), euid = geteuid();
181 
182     if (!(which->flags & TOYFLAG_STAYROOT)) {
183       if (uid != euid) {
184         if (setuid(uid)) perror_exit("setuid %d->%d", euid, uid); // drop root
185         euid = uid;
186         toys.wasroot++;
187       }
188     } else if (CFG_TOYBOX_DEBUG && uid && which != toy_list)
189       error_msg("Not installed suid root");
190 
191     if ((which->flags & TOYFLAG_NEEDROOT) && euid) {
192       toys.which = which;
193       check_help(argv+1);
194       help_exit("Not root");
195     }
196   }
197 
198   // Free old toys contents (to be reentrant), but leave rebound if any
199   // don't blank old optargs if our new argc lives in the old optargs.
200   if (argv<toys.optargs || argv>toys.optargs+toys.optc) free(toys.optargs);
201   memset(&toys, 0, offsetof(struct toy_context, rebound));
202   if (oldwhich) memset(&this, 0, sizeof(this));
203 
204   // Continue to portion of init needed by standalone commands
205   toy_singleinit(which, argv);
206 }
207 
208 // Run an internal toybox command.
209 // Only returns if it can't run command internally, otherwise xexit() when done.
toy_exec_which(struct toy_list * which,char * argv[])210 static void toy_exec_which(struct toy_list *which, char *argv[])
211 {
212   // Return if we can't find it (which includes no multiplexer case),
213   if (!which || (which->flags&TOYFLAG_NOFORK)) return;
214 
215   // Return if stack depth getting noticeable (proxy for leaked heap, etc).
216 
217   // Compiler writers have decided subtracting char * is undefined behavior,
218   // so convert to integers. (LP64 says sizeof(long)==sizeof(pointer).)
219   // Signed typecast so stack growth direction is irrelevant: we're measuring
220   // the distance between two pointers on the same stack, hence the labs().
221   if (!CFG_TOYBOX_NORECURSE && toys.stacktop)
222     if (labs((long)toys.stacktop-(long)&which)>6000) return;
223 
224   // Return if we need to re-exec to acquire root via suid bit.
225   if (toys.which && (which->flags&TOYFLAG_ROOTONLY) && toys.wasroot) return;
226 
227   // Run command
228   toy_init(which, argv);
229   if (toys.which) toys.which->toy_main();
230   xexit();
231 }
232 
233 // Lookup internal toybox command to run via argv[0]
toy_exec(char * argv[])234 void toy_exec(char *argv[])
235 {
236   toy_exec_which(toy_find(*argv), argv);
237 }
238 
239 // Multiplexer command, first argument is command to run, rest are args to that.
240 // If first argument starts with - output list of command install paths.
toybox_main(void)241 void toybox_main(void)
242 {
243   char *toy_paths[] = {"usr/", "bin/", "sbin/", 0}, *s = toys.argv[1];
244   int i, len = 0;
245   unsigned width = 80;
246 
247   // fast path: try to exec immediately.
248   // (Leave toys.which null to disable suid return logic.)
249   // Try dereferencing symlinks until we hit a recognized name
250   while (s) {
251     char *ss = basename(s);
252     struct toy_list *tl = toy_find(ss);
253 
254     if (tl==toy_list && s!=toys.argv[1]) unknown(ss);
255     toy_exec_which(tl, toys.argv+1);
256     s = (0<readlink(s, libbuf, sizeof(libbuf))) ? libbuf : 0;
257   }
258 
259   // For early error reporting
260   toys.which = toy_list;
261 
262   if (toys.argv[1] && strcmp(toys.argv[1], "--long")) unknown(toys.argv[1]);
263 
264   // Output list of commands.
265   terminal_size(&width, 0);
266   for (i = 1; i<ARRAY_LEN(toy_list); i++) {
267     int fl = toy_list[i].flags;
268     if (fl & TOYMASK_LOCATION) {
269       if (toys.argv[1]) {
270         int j;
271         for (j = 0; toy_paths[j]; j++)
272           if (fl & (1<<j)) len += printf("%s", toy_paths[j]);
273       }
274       len += printf("%s",toy_list[i].name);
275       if (++len > width-15) len = 0;
276       xputc(len ? ' ' : '\n');
277     }
278   }
279   xputc('\n');
280 }
281 
main(int argc,char * argv[])282 int main(int argc, char *argv[])
283 {
284   // don't segfault if our environment is crazy
285   if (!*argv) return 127;
286 
287   // Snapshot stack location so we can detect recursion depth later.
288   // Nommu has special reentry path, !stacktop = "vfork/exec self happened"
289   if (!CFG_TOYBOX_FORK && (0x80 & **argv)) **argv &= 0x7f;
290   else {
291     int stack_start;  // here so probe var won't permanently eat stack
292 
293     toys.stacktop = &stack_start;
294   }
295 
296   // Android before O had non-default SIGPIPE, 7 years = remove in Sep 2024.
297   if (CFG_TOYBOX_ON_ANDROID) signal(SIGPIPE, SIG_DFL);
298 
299   if (CFG_TOYBOX) {
300     // Call the multiplexer with argv[] as its arguments so it can toy_find()
301     toys.argv = argv-1;
302     toybox_main();
303   } else {
304     // single command built standalone with no multiplexer is first list entry
305     toy_singleinit(toy_list, argv);
306     toy_list->toy_main();
307   }
308 
309   xexit();
310 }
311