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