toybox/toys/lsb/mount.c
<<
>>
Prefs
   1/* mount.c - mount filesystems
   2 *
   3 * Copyright 2014 Rob Landley <rob@landley.net>
   4 *
   5 * See http://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/mount.html
   6 * Note: -hV is bad spec, haven't implemented -FsLU yet
   7 * no mtab (/proc/mounts does it) so -n is NOP.
   8 * TODO mount -o loop,autoclear (linux git 96c5865559ce)
   9
  10USE_MOUNT(NEWTOY(mount, "?O:afnrvwt:o*[-rw]", TOYFLAG_BIN|TOYFLAG_STAYROOT))
  11//USE_NFSMOUNT(NEWTOY(nfsmount, "?<2>2", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_STAYROOT))
  12
  13config MOUNT
  14  bool "mount"
  15  default y
  16  help
  17    usage: mount [-afFrsvw] [-t TYPE] [-o OPTION,] [[DEVICE] DIR]
  18
  19    Mount new filesystem(s) on directories. With no arguments, display existing
  20    mounts.
  21
  22    -a  mount all entries in /etc/fstab (with -t, only entries of that TYPE)
  23    -O  only mount -a entries that have this option
  24    -f  fake it (don't actually mount)
  25    -r  read only (same as -o ro)
  26    -w  read/write (default, same as -o rw)
  27    -t  specify filesystem type
  28    -v  verbose
  29
  30    OPTIONS is a comma separated list of options, which can also be supplied
  31    as --longopts.
  32
  33    This mount autodetects loopback mounts (a file on a directory) and
  34    bind mounts (file on file, directory on directory), so you don't need
  35    to say --bind or --loop. You can also "mount -a /path" to mount everything
  36    in /etc/fstab under /path, even if it's noauto.
  37
  38#config NFSMOUNT
  39#  bool "nfsmount"
  40#  default n
  41#  help
  42#    usage: nfsmount SHARE DIR
  43#
  44#    Invoke an eldrich horror from the dawn of time.
  45*/
  46
  47#define FOR_mount
  48#include "toys.h"
  49
  50GLOBALS(
  51  struct arg_list *optlist;
  52  char *type;
  53  char *bigO;
  54
  55  unsigned long flags;
  56  char *opts;
  57  int okuser;
  58)
  59
  60// mount.tests should check for all of this:
  61// TODO detect existing identical mount (procfs with different dev name?)
  62// TODO user, users, owner, group, nofail
  63// TODO -p (passfd)
  64// TODO -a -t notype,type2
  65// TODO --subtree
  66// TODO --rbind, -R
  67// TODO make "mount --bind,ro old new" work (implicit -o remount)
  68// TODO mount -a
  69// TODO mount -o remount
  70// TODO fstab: lookup default options for mount
  71// TODO implement -v
  72// TODO "mount -a -o remount,ro" should detect overmounts
  73// TODO work out how that differs from "mount -ar"
  74// TODO what if you --bind mount a block device somewhere (file, dir, dev)
  75// TODO "touch servername; mount -t cifs servername path"
  76// TODO mount -o remount a user mount
  77// TODO mount image.img sub (auto-loopback) then umount image.img
  78
  79// Strip flags out of comma separated list of options, return flags,.
  80static long flag_opts(char *new, long flags, char **more)
  81{
  82  struct {
  83    char *name;
  84    long flags;
  85  } opts[] = {
  86    // NOPs (we autodetect --loop and --bind)
  87    {"loop", 0}, {"bind", 0}, {"defaults", 0}, {"quiet", 0},
  88    {"user", 0}, {"nouser", 0}, // checked in fstab, ignored in -o
  89    {"ro", MS_RDONLY}, {"rw", ~MS_RDONLY},
  90    {"nosuid", MS_NOSUID}, {"suid", ~MS_NOSUID},
  91    {"nodev", MS_NODEV}, {"dev", ~MS_NODEV},
  92    {"noexec", MS_NOEXEC}, {"exec", ~MS_NOEXEC},
  93    {"sync", MS_SYNCHRONOUS}, {"async", ~MS_SYNCHRONOUS},
  94    {"noatime", MS_NOATIME}, {"atime", ~MS_NOATIME},
  95    {"norelatime", ~MS_RELATIME}, {"relatime", MS_RELATIME},
  96    {"nodiratime", MS_NODIRATIME}, {"diratime", ~MS_NODIRATIME},
  97    {"loud", ~MS_SILENT},
  98    {"shared", MS_SHARED}, {"rshared", MS_SHARED|MS_REC},
  99    {"slave", MS_SLAVE}, {"rslave", MS_SLAVE|MS_REC},
 100    {"private", MS_PRIVATE}, {"rprivate", MS_SLAVE|MS_REC},
 101    {"unbindable", MS_UNBINDABLE}, {"runbindable", MS_UNBINDABLE|MS_REC},
 102    {"remount", MS_REMOUNT}, {"move", MS_MOVE},
 103    // mand dirsync rec iversion strictatime
 104  };
 105
 106  if (new) for (;;) {
 107    char *comma = strchr(new, ',');
 108    int i;
 109
 110    if (comma) *comma = 0;
 111
 112    // If we recognize an option, apply flags
 113    for (i = 0; i < ARRAY_LEN(opts); i++) if (!strcasecmp(opts[i].name, new)) {
 114      long ll = opts[i].flags;
 115
 116      if (ll < 0) flags &= ll;
 117      else flags |= ll;
 118
 119      break;
 120    }
 121
 122    // If we didn't recognize it, keep string version
 123    if (more && i == ARRAY_LEN(opts)) {
 124      i = *more ? strlen(*more) : 0;
 125      *more = xrealloc(*more, i + strlen(new) + 2);
 126      if (i) (*more)[i++] = ',';
 127      strcpy(i+*more, new);
 128    }
 129
 130    if (!comma) break;
 131    *comma = ',';
 132    new = comma + 1;
 133  }
 134
 135  return flags;
 136}
 137
 138static void mount_filesystem(char *dev, char *dir, char *type,
 139  unsigned long flags, char *opts)
 140{
 141  FILE *fp = 0;
 142  int rc = EINVAL;
 143  char *buf = 0;
 144
 145  if (toys.optflags & FLAG_f) return;
 146
 147  if (getuid()) {
 148    if (TT.okuser) TT.okuser = 0;
 149    else {
 150      error_msg("'%s' not user mountable in fstab", dev);
 151
 152      return;
 153    }
 154  }
 155
 156  // Autodetect bind mount or filesystem type
 157
 158  if (type && !strcmp(type, "auto")) type = 0;
 159  if (flags & MS_MOVE) {
 160    if (type) error_exit("--move with -t");
 161  } else if (!type) {
 162    struct stat stdev, stdir;
 163
 164    // file on file or dir on dir is a --bind mount.
 165    if (!stat(dev, &stdev) && !stat(dir, &stdir)
 166        && ((S_ISREG(stdev.st_mode) && S_ISREG(stdir.st_mode))
 167            || (S_ISDIR(stdev.st_mode) && S_ISDIR(stdir.st_mode))))
 168    {
 169      flags |= MS_BIND;
 170    } else fp = xfopen("/proc/filesystems", "r");
 171  } else if (!strcmp(type, "ignore")) return;
 172  else if (!strcmp(type, "swap"))
 173    toys.exitval |= xrun((char *[]){"swapon", "--", dev, 0});
 174
 175  for (;;) {
 176    int fd = -1, ro = 0;
 177
 178    // If type wasn't specified, try all of them in order.
 179    if (fp && !buf) {
 180      size_t i;
 181
 182      if (getline(&buf, &i, fp)<0) {
 183        error_msg("%s: need -t", dev);
 184        break;
 185      }
 186      type = buf;
 187      // skip nodev devices
 188      if (!isspace(*type)) {
 189        free(buf);
 190        buf = 0;
 191
 192        continue;
 193      }
 194      // trim whitespace
 195      while (isspace(*type)) type++;
 196      i = strlen(type);
 197      if (i) type[i-1] = 0;
 198    }
 199    if (toys.optflags & FLAG_v)
 200      printf("try '%s' type '%s' on '%s'\n", dev, type, dir);
 201    for (;;) {
 202      rc = mount(dev, dir, type, flags, opts);
 203      // Did we succeed, fail unrecoverably, or already try read-only?
 204      if (!rc || (errno != EACCES && errno != EROFS) || (flags&MS_RDONLY))
 205        break;
 206      // If we haven't already tried it, use the BLKROSET ioctl to ensure
 207      // that the underlying device isn't read-only.
 208      if (fd == -1) {
 209        if (toys.optflags & FLAG_v)
 210          printf("trying BLKROSET ioctl on '%s'\n", dev);
 211        if (-1 != (fd = open(dev, O_RDONLY))) {
 212          rc = ioctl(fd, BLKROSET, &ro);
 213          close(fd);
 214          if (!rc) continue;
 215        }
 216      }
 217      fprintf(stderr, "'%s' is read-only\n", dev);
 218      flags |= MS_RDONLY;
 219    }
 220
 221    // Trying to autodetect loop mounts like bind mounts above (file on dir)
 222    // isn't good enough because "mount -t ext2 fs.img dir" is valid, but if
 223    // you _do_ accept loop mounts with -t how do you tell "-t cifs" isn't
 224    // looking for a block device if it's not in /proc/filesystems yet
 225    // because the module that won't be loaded until you try the mount, and
 226    // if you can't then DEVICE existing as a file would cause a false
 227    // positive loopback mount (so "touch servername" becomes a potential
 228    // denial of service attack...)
 229    //
 230    // Solution: try the mount, let the kernel tell us it wanted a block
 231    // device, then do the loopback setup and retry the mount.
 232
 233    if (rc && errno == ENOTBLK) {
 234      char *losetup[] = {"losetup", "-fs", dev, 0};
 235      int pipe, len;
 236      pid_t pid;
 237
 238      if (flags & MS_RDONLY) losetup[1] = "-fsr";
 239      pid = xpopen(losetup, &pipe, 1);
 240      len = readall(pipe, toybuf, sizeof(toybuf)-1);
 241      rc = xpclose(pid, pipe);
 242      if (!rc && len > 1) {
 243        if (toybuf[len-1] == '\n') --len;
 244        toybuf[len] = 0;
 245        dev = toybuf;
 246
 247        continue;
 248      }
 249      error_msg("losetup failed %d", rc);
 250
 251      break;
 252    }
 253
 254    free(buf);
 255    buf = 0;
 256    if (!rc) break;
 257    if (fp && (errno == EINVAL || errno == EBUSY)) continue;
 258
 259    perror_msg("'%s'->'%s'", dev, dir);
 260
 261    break;
 262  }
 263  if (fp) fclose(fp);
 264}
 265
 266void mount_main(void)
 267{
 268  char *opts = 0, *dev = 0, *dir = 0, **ss;
 269  long flags = MS_SILENT;
 270  struct arg_list *o;
 271  struct mtab_list *mtl, *mtl2 = 0, *mm, *remount;
 272
 273// TODO
 274// remount
 275//   - overmounts
 276// shared subtree
 277// -o parsed after fstab options
 278// test if mountpoint already exists (-o noremount?)
 279
 280  // First pass; just accumulate string, don't parse flags yet. (This is so
 281  // we can modify fstab entries with -a, or mtab with remount.)
 282  for (o = TT.optlist; o; o = o->next) comma_collate(&opts, o->arg);
 283  if (toys.optflags & FLAG_r) comma_collate(&opts, "ro");
 284  if (toys.optflags & FLAG_w) comma_collate(&opts, "rw");
 285
 286  // Treat each --option as -o option
 287  for (ss = toys.optargs; *ss; ss++) {
 288    char *sss = *ss;
 289
 290    // If you realy, really want to mount a file named "--", we support it.
 291    if (sss[0]=='-' && sss[1]=='-' && sss[2]) comma_collate(&opts, sss+2);
 292    else if (!dev) dev = sss;
 293    else if (!dir) dir = sss;
 294    // same message as lib/args.c ">2" which we can't use because --opts count
 295    else error_exit("Max 2 arguments\n");
 296  }
 297
 298  if ((toys.optflags & FLAG_a) && dir) error_exit("-a with >1 arg");
 299
 300  // For remount we need _last_ match (in case of overmounts), so traverse
 301  // in reverse order. (Yes I'm using remount as a boolean for a bit here,
 302  // the double cast is to get gcc to shut up about it.)
 303  remount = (void *)(long)comma_scan(opts, "remount", 0);
 304  if (((toys.optflags & FLAG_a) && !access("/proc/mounts", R_OK)) || remount) {
 305    mm = dlist_terminate(mtl = mtl2 = xgetmountlist(0));
 306    if (remount) remount = mm;
 307  }
 308
 309  // Do we need to do an /etc/fstab trawl?
 310  // This covers -a, -o remount, one argument, all user mounts
 311  if ((toys.optflags & FLAG_a) || (dev && (!dir || getuid() || remount))) {
 312    if (!remount) dlist_terminate(mtl = xgetmountlist("/etc/fstab"));
 313
 314    for (mm = remount ? remount : mtl; mm; mm = (remount ? mm->prev : mm->next))
 315    {
 316      char *aopts = 0;
 317      struct mtab_list *mmm = 0;
 318      int aflags, noauto, len;
 319
 320      // Check for noauto and get it out of the option list. (Unknown options
 321      // that make it to the kernel give filesystem drivers indigestion.)
 322      noauto = comma_scan(mm->opts, "noauto", 1);
 323
 324      if (toys.optflags & FLAG_a) {
 325        // "mount -a /path" to mount all entries under /path
 326        if (dev) {
 327           len = strlen(dev);
 328           if (strncmp(dev, mm->dir, len)
 329               || (mm->dir[len] && mm->dir[len] != '/')) continue;
 330        } else if (noauto) continue; // never present in the remount case
 331        if (!mountlist_istype(mm,TT.type) || !comma_scanall(mm->opts,TT.bigO))
 332          continue;
 333      } else {
 334        if (dir && strcmp(dir, mm->dir)) continue;
 335        if (dev && strcmp(dev, mm->device) && (dir || strcmp(dev, mm->dir)))
 336          continue;
 337      }
 338
 339      // Don't overmount the same dev on the same directory
 340      // (Unless root explicitly says to in non -a mode.)
 341      if (mtl2 && !remount)
 342        for (mmm = mtl2; mmm; mmm = mmm->next)
 343          if (!strcmp(mm->dir, mmm->dir) && !strcmp(mm->device, mmm->device))
 344            break;
 345 
 346      // user only counts from fstab, not opts.
 347      if (!mmm) {
 348        TT.okuser = comma_scan(mm->opts, "user", 1);
 349        aflags = flag_opts(mm->opts, flags, &aopts);
 350        aflags = flag_opts(opts, aflags, &aopts);
 351
 352        mount_filesystem(mm->device, mm->dir, mm->type, aflags, aopts);
 353      } // TODO else if (getuid()) error_msg("already there") ?
 354      free(aopts);
 355
 356      if (!(toys.optflags & FLAG_a)) break;
 357    }
 358    if (CFG_TOYBOX_FREE) {
 359      llist_traverse(mtl, free);
 360      llist_traverse(mtl2, free);
 361    }
 362    if (!mm && !(toys.optflags & FLAG_a))
 363      error_exit("'%s' not in %s", dir ? dir : dev,
 364                 remount ? "/proc/mounts" : "fstab");
 365
 366  // show mounts from /proc/mounts
 367  } else if (!dev) {
 368    for (mtl = xgetmountlist(0); mtl && (mm = dlist_pop(&mtl)); free(mm)) {
 369      char *s = 0;
 370
 371      if (TT.type && strcmp(TT.type, mm->type)) continue;
 372      if (*mm->device == '/') s = xabspath(mm->device, 0);
 373      xprintf("%s on %s type %s (%s)\n",
 374              s ? s : mm->device, mm->dir, mm->type, mm->opts);
 375      free(s);
 376    }
 377
 378  // two arguments
 379  } else {
 380    char *more = 0;
 381
 382    flags = flag_opts(opts, flags, &more);
 383    mount_filesystem(dev, dir, TT.type, flags, more);
 384    if (CFG_TOYBOX_FREE) free(more);
 385  }
 386}
 387