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