1 /* Toybox infrastructure.
2  *
3  * Copyright 2006 Rob Landley <rob@landley.net>
4  */
5 
6 #include "toys.h"
7 
8 
9 // Populate toy_list[].
10 
11 #undef NEWTOY
12 #undef OLDTOY
13 #define NEWTOY(name, opts, flags) {#name, name##_main, OPTSTR_##name, flags},
14 #define OLDTOY(name, oldname, flags) \
15   {#name, oldname##_main, OPTSTR_##oldname, flags},
16 
17 struct toy_list toy_list[] = {
18 #include "generated/newtoys.h"
19 };
20 
21 // global context for this command.
22 
23 struct toy_context toys;
24 union global_union this;
25 char toybuf[4096], libbuf[4096];
26 
toy_find(char *name)27 struct toy_list *toy_find(char *name)
28 {
29   int top, bottom, middle;
30 
31   if (!CFG_TOYBOX || strchr(name, '/')) return 0;
32 
33   // If the name starts with "toybox" accept that as a match.  Otherwise
34   // skip the first entry, which is out of order.
35 
36   if (!strncmp(name, "toybox", 6)) return toy_list;
37   bottom = 1;
38 
39   // Binary search to find this command.
40 
41   top = ARRAY_LEN(toy_list)-1;
42   for (;;) {
43     int result;
44 
45     middle = (top+bottom)/2;
46     if (middle<bottom || middle>top) return 0;
47     result = strcmp(name,toy_list[middle].name);
48     if (!result) return toy_list+middle;
49     if (result<0) top = --middle;
50     else bottom = ++middle;
51   }
52 }
53 
54 // Figure out whether or not anything is using the option parsing logic,
55 // because the compiler can't figure out whether or not to optimize it away
56 // on its' own.  NEED_OPTIONS becomes a constant allowing if() to optimize
57 // stuff out via dead code elimination.
58 
59 #undef NEWTOY
60 #undef OLDTOY
61 #define NEWTOY(name, opts, flags) opts ||
62 #define OLDTOY(name, oldname, flags) OPTSTR_##oldname ||
63 static const int NEED_OPTIONS =
64 #include "generated/newtoys.h"
65 0;  // Ends the opts || opts || opts...
66 
unknown(char *name)67 static void unknown(char *name)
68 {
69   toys.exitval = 127;
70   toys.which = toy_list;
71   error_exit("Unknown command %s", name);
72 }
73 
74 // Setup toybox global state for this command.
toy_singleinit(struct toy_list *which, char *argv[])75 static void toy_singleinit(struct toy_list *which, char *argv[])
76 {
77   toys.which = which;
78   toys.argv = argv;
79 
80   if (CFG_TOYBOX_I18N) setlocale(LC_CTYPE, "C.UTF-8");
81   setlinebuf(stdout);
82 
83   // Parse --help and --version for (almost) all commands
84   if (CFG_TOYBOX_HELP_DASHDASH && !(which->flags & TOYFLAG_NOHELP) && argv[1]) {
85     if (!strcmp(argv[1], "--help")) {
86       if (CFG_TOYBOX && toys.which == toy_list && toys.argv[2])
87         if (!(toys.which = toy_find(toys.argv[2]))) unknown(toys.argv[2]);
88       show_help(stdout);
89       xexit();
90     }
91 
92     if (!strcmp(argv[1], "--version")) {
93       xputs("toybox "TOYBOX_VERSION);
94       xexit();
95     }
96   }
97 
98   if (NEED_OPTIONS && which->options) get_optflags();
99   else {
100     toys.optargs = argv+1;
101     for (toys.optc = 0; toys.optargs[toys.optc]; toys.optc++);
102   }
103   toys.old_umask = umask(0);
104   if (!(which->flags & TOYFLAG_UMASK)) umask(toys.old_umask);
105   toys.signalfd--;
106   toys.toycount = ARRAY_LEN(toy_list);
107 }
108 
109 // Full init needed by multiplexer or reentrant calls, calls singleinit at end
toy_init(struct toy_list *which, char *argv[])110 void toy_init(struct toy_list *which, char *argv[])
111 {
112   void *oldwhich = toys.which;
113 
114   // Drop permissions for non-suid commands.
115 
116   if (CFG_TOYBOX_SUID) {
117     if (!toys.which) toys.which = toy_list;
118 
119     uid_t uid = getuid(), euid = geteuid();
120 
121     if (!(which->flags & TOYFLAG_STAYROOT)) {
122       if (uid != euid) {
123         if (setuid(uid)) perror_exit("setuid %d->%d", euid, uid); // drop root
124         euid = uid;
125         toys.wasroot++;
126       }
127     } else if (CFG_TOYBOX_DEBUG && uid && which != toy_list)
128       error_msg("Not installed suid root");
129 
130     if ((which->flags & TOYFLAG_NEEDROOT) && euid != KERNEL_PROCESS_GROUP) help_exit("Not root");
131   }
132 
133   // Free old toys contents (to be reentrant), but leave rebound if any
134   // don't blank old optargs if our new argc lives in the old optargs.
135   if (argv<toys.optargs || argv>toys.optargs+toys.optc) free(toys.optargs);
136   memset(&toys, 0, offsetof(struct toy_context, rebound));
137   if (oldwhich) memset(&this, 0, sizeof(this));
138 
139   // Continue to portion of init needed by standalone commands
140   toy_singleinit(which, argv);
141 }
142 
143 // Run an internal toybox command.
144 // Only returns if it can't run command internally, otherwise xexit() when done.
toy_exec_which(struct toy_list *which, char *argv[])145 void toy_exec_which(struct toy_list *which, char *argv[])
146 {
147   // Return if we can't find it (which includes no multiplexer case),
148   if (!which) return;
149 
150   // Return if stack depth getting noticeable (proxy for leaked heap, etc).
151 
152   // Compiler writers have decided subtracting char * is undefined behavior,
153   // so convert to integers. (LP64 says sizeof(long)==sizeof(pointer).)
154   // Signed typecast so stack growth direction is irrelevant: we're measuring
155   // the distance between two pointers on the same stack, hence the labs().
156   if (!CFG_TOYBOX_NORECURSE && toys.stacktop)
157     if (labs((long)toys.stacktop-(long)&which)>6000) return;
158 
159   // Return if we need to re-exec to acquire root via suid bit.
160   if (toys.which && (which->flags&TOYFLAG_ROOTONLY) && toys.wasroot) return;
161 
162   // Run command
163   toy_init(which, argv);
164   if (toys.which) toys.which->toy_main();
165   xexit();
166 }
167 
168 // Lookup internal toybox command to run via argv[0]
toy_exec(char *argv[])169 void toy_exec(char *argv[])
170 {
171   toy_exec_which(toy_find(basename(*argv)), argv);
172 }
173 
174 // Multiplexer command, first argument is command to run, rest are args to that.
175 // If first argument starts with - output list of command install paths.
toybox_main(void)176 void toybox_main(void)
177 {
178   static char *toy_paths[]={"usr/","bin/","sbin/",0};
179   int i, len = 0;
180 
181   // fast path: try to exec immediately.
182   // (Leave toys.which null to disable suid return logic.)
183   // Try dereferencing one layer of symlink
184   if (toys.argv[1]) {
185     toy_exec(toys.argv+1);
186     if (0<readlink(toys.argv[1], libbuf, sizeof(libbuf))) {
187       struct toy_list *tl= toy_find(basename(libbuf));
188 
189       if (tl == toy_list) unknown(basename(toys.argv[1]));
190       else toy_exec_which(tl, toys.argv+1);
191     }
192   }
193 
194   // For early error reporting
195   toys.which = toy_list;
196 
197   if (toys.argv[1] && toys.argv[1][0] != '-') unknown(toys.argv[1]);
198 
199   // Output list of command.
200   for (i=1; i<ARRAY_LEN(toy_list); i++) {
201     int fl = toy_list[i].flags;
202     if (fl & TOYMASK_LOCATION) {
203       if (toys.argv[1]) {
204         int j;
205         for (j=0; toy_paths[j]; j++)
206           if (fl & (1<<j)) len += printf("%s", toy_paths[j]);
207       }
208       len += printf("%s",toy_list[i].name);
209       if (++len > 65) len = 0;
210       xputc(len ? ' ' : '\n');
211     }
212   }
213   xputc('\n');
214 }
215 
main(int argc, char *argv[])216 int main(int argc, char *argv[])
217 {
218   if (!*argv) return 127;
219 
220   // Snapshot stack location so we can detect recursion depth later.
221   // This is its own block so probe doesn't permanently consume stack.
222   else {
223     int stack;
224 
225     toys.stacktop = &stack;
226   }
227 
228   // Up to and including Android M, bionic's dynamic linker added a handler to
229   // cause a crash dump on SIGPIPE. That was removed in Android N, but adbd
230   // was still setting the SIGPIPE disposition to SIG_IGN, and its children
231   // were inheriting that. In Android O, adbd is fixed, but manually asking
232   // for the default disposition is harmless, and it'll be a long time before
233   // no one's using anything older than O!
234   if (CFG_TOYBOX_ON_ANDROID) signal(SIGPIPE, SIG_DFL);
235 
236   // If nommu can't fork, special reentry path.
237   // Use !stacktop to signal "vfork happened", both before and after xexec()
238   if (!CFG_TOYBOX_FORK) {
239     if (0x80 & **argv) {
240       **argv &= 0x7f;
241       toys.stacktop = 0;
242     }
243   }
244 
245   if (CFG_TOYBOX) {
246     // Call the multiplexer, adjusting this argv[] to be its' argv[1].
247     // (It will adjust it back before calling toy_exec().)
248     toys.argv = argv-1;
249     toybox_main();
250   } else {
251     // a single toybox command built standalone with no multiplexer
252     toy_singleinit(toy_list, argv);
253     toy_list->toy_main();
254   }
255 
256   xexit();
257 }
258