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