main.c 8.6 KB

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