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 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 if (!CFG_TOYBOX_HELP_DASHDASH || !*arg) return;
136 if (!CFG_TOYBOX || toys.which != toy_list)
137 if (toys.which->flags&TOYFLAG_NOHELP) return;
138
139 if (!strcmp(*arg, "--help")) {
140 if (CFG_TOYBOX && toys.which == toy_list && arg[1]) {
141 toys.which = 0;
142 if (!(toys.which = toy_find(arg[1]))) unknown(arg[1]);
143 }
144 show_help(stdout, HELP_HEADER);
145 xexit();
146 }
147
148 if (!strcmp(*arg, "--version")) {
149 xprintf("toybox %s\n", toybox_version);
150 xexit();
151 }
152 }
153
154 // Setup toybox global state for this command.
toy_singleinit(struct toy_list * which,char * argv[])155 void toy_singleinit(struct toy_list *which, char *argv[])
156 {
157 toys.which = which;
158 toys.argv = argv;
159 toys.toycount = ARRAY_LEN(toy_list);
160
161 if (NEED_OPTIONS && which->options) get_optflags();
162 else {
163 check_help(toys.optargs = argv+1);
164 for (toys.optc = 0; toys.optargs[toys.optc]; toys.optc++);
165 }
166
167 // Setup we only want to do once: skip for multiplexer or NOFORK reentry
168 if (!(CFG_TOYBOX && which == toy_list) && !(which->flags & TOYFLAG_NOFORK)) {
169 char *buf = 0;
170 int btype = _IOFBF;
171
172 toys.old_umask = umask(0);
173 if (!(which->flags & TOYFLAG_UMASK)) umask(toys.old_umask);
174
175 // Try user's locale, but if that isn't UTF-8 merge in a UTF-8 locale's
176 // character type data. (Fall back to en_US for MacOS.)
177 setlocale(LC_CTYPE, "");
178 if (strcmp("UTF-8", nl_langinfo(CODESET)))
179 uselocale(newlocale(LC_CTYPE_MASK, "C.UTF-8", 0) ? :
180 newlocale(LC_CTYPE_MASK, "en_US.UTF-8", 0));
181
182 if (which->flags & TOYFLAG_LINEBUF) btype = _IOLBF;
183 else if (which->flags & TOYFLAG_NOBUF) btype = _IONBF;
184 else buf = xmalloc(4096);
185 setvbuf(stdout, buf, btype, buf ? 4096 : 0);
186 }
187 }
188
189 // Full init needed by multiplexer or reentrant calls, calls singleinit at end
toy_init(struct toy_list * which,char * argv[])190 void toy_init(struct toy_list *which, char *argv[])
191 {
192 void *oldwhich = toys.which;
193
194 // Drop permissions for non-suid commands.
195 if (CFG_TOYBOX_SUID) {
196 if (!toys.which) toys.which = toy_list;
197
198 uid_t uid = getuid(), euid = geteuid();
199
200 if (!(which->flags & TOYFLAG_STAYROOT)) {
201 if (uid != euid) {
202 if (setuid(uid)) perror_exit("setuid %d->%d", euid, uid); // drop root
203 euid = uid;
204 toys.wasroot++;
205 }
206 } else if (CFG_TOYBOX_DEBUG && uid && which != toy_list)
207 error_msg("Not installed suid root");
208
209 if ((which->flags & TOYFLAG_NEEDROOT) && euid) {
210 toys.which = which;
211 check_help(argv+1);
212 help_exit("Not root");
213 }
214 }
215
216 memset(&toys, 0, offsetof(struct toy_context, rebound));
217 if (oldwhich) memset(&this, 0, sizeof(this));
218
219 // Continue to portion of init needed by standalone commands
220 toy_singleinit(which, argv);
221 }
222
223 // Run an internal toybox command.
224 // Only returns if it can't run command internally, otherwise xexit() when done.
toy_exec_which(struct toy_list * which,char * argv[])225 void toy_exec_which(struct toy_list *which, char *argv[])
226 {
227 // Return if we can't find it (which includes no multiplexer case),
228 if (!which || (which->flags&TOYFLAG_NOFORK)) return;
229
230 // Return if stack depth getting noticeable (proxy for leaked heap, etc).
231
232 // Compiler writers have decided subtracting char * is undefined behavior,
233 // so convert to integers. (LP64 says sizeof(long)==sizeof(pointer).)
234 // Signed typecast so stack growth direction is irrelevant: we're measuring
235 // the distance between two pointers on the same stack, hence the labs().
236 if (!CFG_TOYBOX_NORECURSE && toys.stacktop)
237 if (labs((long)toys.stacktop-(long)&which)>24000) return;
238
239 // Return if we need to re-exec to acquire root via suid bit.
240 if (toys.which && (which->flags&TOYFLAG_ROOTONLY) && toys.wasroot) return;
241
242 // Run command
243 toy_init(which, argv);
244 if (toys.which) toys.which->toy_main();
245 xexit();
246 }
247
248 // Lookup internal toybox command to run via argv[0]
toy_exec(char * argv[])249 void toy_exec(char *argv[])
250 {
251 toy_exec_which(toy_find(*argv), argv);
252 }
253
254 // Multiplexer command, first argument is command to run, rest are args to that.
255 // If first argument starts with - output list of command install paths.
toybox_main(void)256 void toybox_main(void)
257 {
258 char *toy_paths[] = {"usr/", "bin/", "sbin/", 0}, *s = toys.argv[1];
259 int i, len = 0;
260 unsigned width = 80;
261
262 // fast path: try to exec immediately.
263 // (Leave toys.which null to disable suid return logic.)
264 // Try dereferencing symlinks until we hit a recognized name
265 while (s) {
266 char *ss = basename(s);
267 struct toy_list *tl = toy_find(ss);
268
269 if (tl==toy_list && s!=toys.argv[1]) unknown(ss);
270 toy_exec_which(tl, toys.argv+1);
271 s = (0<readlink(s, libbuf, sizeof(libbuf))) ? libbuf : 0;
272 }
273
274 // For early error reporting
275 toys.which = toy_list;
276
277 if (toys.argv[1] && strcmp(toys.argv[1], "--long")) unknown(toys.argv[1]);
278
279 // Output list of commands.
280 terminal_size(&width, 0);
281 for (i = 1; i<ARRAY_LEN(toy_list); i++) {
282 int fl = toy_list[i].flags;
283 if (fl & TOYMASK_LOCATION) {
284 if (toys.argv[1]) {
285 int j;
286 for (j = 0; toy_paths[j]; j++)
287 if (fl & (1<<j)) len += printf("%s", toy_paths[j]);
288 }
289 len += printf("%s",toy_list[i].name);
290 if (++len > width-15) len = 0;
291 xputc(len ? ' ' : '\n');
292 }
293 }
294 xputc('\n');
295 }
296
main(int argc,char * argv[])297 int main(int argc, char *argv[])
298 {
299 // don't segfault if our environment is crazy
300 // TODO mooted by kernel commit dcd46d897adb7 5.17 kernel Jan 2022
301 if (!*argv) return 127;
302
303 // Snapshot stack location so we can detect recursion depth later.
304 // Nommu has special reentry path, !stacktop = "vfork/exec self happened"
305 if (!CFG_TOYBOX_FORK && (0x80 & **argv)) **argv &= 0x7f;
306 else {
307 int stack_start; // here so probe var won't permanently eat stack
308
309 toys.stacktop = &stack_start;
310 }
311
312 // Android before O had non-default SIGPIPE, 7 years = remove in Sep 2024.
313 if (CFG_TOYBOX_ON_ANDROID) signal(SIGPIPE, SIG_DFL);
314
315 if (CFG_TOYBOX) {
316 // Call the multiplexer with argv[] as its arguments so it can toy_find()
317 toys.argv = argv-1;
318 toybox_main();
319 } else {
320 // single command built standalone with no multiplexer is first list entry
321 toy_singleinit(toy_list, argv);
322 toy_list->toy_main();
323 }
324
325 xexit();
326 }
327