main.c 8.8 KB

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