xref: /third_party/toybox/toys/lsb/mount.c (revision 0f66f451)
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#  default 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 (!s) 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)<1) {
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      continue;
274    }
275
276    free(buf);
277    buf = 0;
278    if (!rc) break;
279    if (fp && (errno == EINVAL || errno == EBUSY)) continue;
280
281    perror_msg("'%s'->'%s'", dev, dir);
282
283    break;
284  }
285  if (fp) fclose(fp);
286}
287
288void mount_main(void)
289{
290  char *opts = 0, *dev = 0, *dir = 0, **ss;
291  long flags = MS_SILENT;
292  struct arg_list *o;
293  struct mtab_list *mtl, *mtl2 = 0, *mm, *remount;
294
295// TODO
296// remount
297//   - overmounts
298// shared subtree
299// -o parsed after fstab options
300// test if mountpoint already exists (-o noremount?)
301
302  // First pass; just accumulate string, don't parse flags yet. (This is so
303  // we can modify fstab entries with -a, or mtab with remount.)
304  for (o = TT.optlist; o; o = o->next) comma_collate(&opts, o->arg);
305  if (FLAG(r)) comma_collate(&opts, "ro");
306  if (FLAG(w)) comma_collate(&opts, "rw");
307
308  // Treat each --option as -o option
309  for (ss = toys.optargs; *ss; ss++) {
310    char *sss = *ss;
311
312    // If you realy, really want to mount a file named "--", we support it.
313    if (sss[0]=='-' && sss[1]=='-' && sss[2]) comma_collate(&opts, sss+2);
314    else if (!dev) dev = sss;
315    else if (!dir) dir = sss;
316    // same message as lib/args.c ">2" which we can't use because --opts count
317    else error_exit("Max 2 arguments\n");
318  }
319
320  if (FLAG(a) && dir) error_exit("-a with >1 arg");
321
322  // For remount we need _last_ match (in case of overmounts), so traverse
323  // in reverse order. (Yes I'm using remount as a boolean for a bit here,
324  // the double cast is to get gcc to shut up about it.)
325  remount = (void *)(long)comma_scan(opts, "remount", 0);
326  if ((FLAG(a) && !access("/proc/mounts", R_OK)) || remount) {
327    mm = dlist_terminate(mtl = mtl2 = xgetmountlist(0));
328    if (remount) remount = mm;
329  }
330
331  // Do we need to do an /etc/fstab trawl?
332  // This covers -a, -o remount, one argument, all user mounts
333  if (FLAG(a) || (dev && (!dir || getuid() || remount))) {
334    if (!remount) dlist_terminate(mtl = xgetmountlist("/etc/fstab"));
335
336    for (mm = remount ? remount : mtl; mm; mm = (remount ? mm->prev : mm->next))
337    {
338      char *aopts = 0;
339      struct mtab_list *mmm = 0;
340      int aflags, noauto, len;
341
342      // Check for noauto and get it out of the option list. (Unknown options
343      // that make it to the kernel give filesystem drivers indigestion.)
344      noauto = comma_scan(mm->opts, "noauto", 1);
345
346      if (FLAG(a)) {
347        // "mount -a /path" to mount all entries under /path
348        if (dev) {
349           len = strlen(dev);
350           if (strncmp(dev, mm->dir, len)
351               || (mm->dir[len] && mm->dir[len] != '/')) continue;
352        } else if (noauto) continue; // never present in the remount case
353        if (!mountlist_istype(mm,TT.type) || !comma_scanall(mm->opts,TT.bigO))
354          continue;
355      } else {
356        if (dir && strcmp(dir, mm->dir)) continue;
357        if (dev && strcmp(dev, mm->device) && (dir || strcmp(dev, mm->dir)))
358          continue;
359      }
360
361      // Don't overmount the same dev on the same directory
362      // (Unless root explicitly says to in non -a mode.)
363      if (mtl2 && !remount)
364        for (mmm = mtl2; mmm; mmm = mmm->next)
365          if (!strcmp(mm->dir, mmm->dir) && !strcmp(mm->device, mmm->device))
366            break;
367
368      // user only counts from fstab, not opts.
369      if (!mmm) {
370        TT.okuser = comma_scan(mm->opts, "user", 1);
371        aflags = flag_opts(mm->opts, flags, &aopts);
372        aflags = flag_opts(opts, aflags, &aopts);
373
374        mount_filesystem(mm->device, mm->dir, mm->type, aflags, aopts);
375      } // TODO else if (getuid()) error_msg("already there") ?
376      free(aopts);
377
378      if (!FLAG(a)) break;
379    }
380    if (CFG_TOYBOX_FREE) {
381      llist_traverse(mtl, free);
382      llist_traverse(mtl2, free);
383    }
384    if (!mm && !FLAG(a))
385      error_exit("'%s' not in %s", dir ? dir : dev,
386                 remount ? "/proc/mounts" : "fstab");
387
388  // show mounts from /proc/mounts
389  } else if (!dev) {
390    for (mtl = xgetmountlist(0); mtl && (mm = dlist_pop(&mtl)); free(mm)) {
391      char *s = 0;
392
393      if (TT.type && strcmp(TT.type, mm->type)) continue;
394      if (*mm->device == '/') s = xabspath(mm->device, 0);
395      xprintf("%s on %s type %s (%s)\n",
396              s ? s : mm->device, mm->dir, mm->type, mm->opts);
397      free(s);
398    }
399
400  // two arguments
401  } else {
402    char *more = 0;
403
404    flags = flag_opts(opts, flags, &more);
405    mount_filesystem(dev, dir, TT.type, flags, more);
406    if (CFG_TOYBOX_FREE) free(more);
407  }
408}
409