• Home
  • History
  • Annotate
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
10 USE_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 
13 config 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 
GLOBALS(struct arg_list * optlist;char * type;char * bigO;unsigned long flags;char * opts;int okuser;)50 GLOBALS(
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,.
80 static 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 
mount_filesystem(char * dev,char * dir,char * type,unsigned long flags,char * opts)138 static 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) break;
183       type = buf;
184       // skip nodev devices
185       if (!isspace(*type)) {
186         free(buf);
187         buf = 0;
188 
189         continue;
190       }
191       // trim whitespace
192       while (isspace(*type)) type++;
193       i = strlen(type);
194       if (i) type[i-1] = 0;
195     }
196     if (toys.optflags & FLAG_v)
197       printf("try '%s' type '%s' on '%s'\n", dev, type, dir);
198     for (;;) {
199       rc = mount(dev, dir, type, flags, opts);
200       // Did we succeed, fail unrecoverably, or already try read-only?
201       if (!rc || (errno != EACCES && errno != EROFS) || (flags&MS_RDONLY))
202         break;
203       // If we haven't already tried it, use the BLKROSET ioctl to ensure
204       // that the underlying device isn't read-only.
205       if (fd == -1) {
206         if (toys.optflags & FLAG_v)
207           printf("trying BLKROSET ioctl on '%s'\n", dev);
208         if (-1 != (fd = open(dev, O_RDONLY))) {
209           rc = ioctl(fd, BLKROSET, &ro);
210           close(fd);
211           if (!rc) continue;
212         }
213       }
214       fprintf(stderr, "'%s' is read-only\n", dev);
215       flags |= MS_RDONLY;
216     }
217 
218     // Trying to autodetect loop mounts like bind mounts above (file on dir)
219     // isn't good enough because "mount -t ext2 fs.img dir" is valid, but if
220     // you _do_ accept loop mounts with -t how do you tell "-t cifs" isn't
221     // looking for a block device if it's not in /proc/filesystems yet
222     // because the module that won't be loaded until you try the mount, and
223     // if you can't then DEVICE existing as a file would cause a false
224     // positive loopback mount (so "touch servername" becomes a potential
225     // denial of service attack...)
226     //
227     // Solution: try the mount, let the kernel tell us it wanted a block
228     // device, then do the loopback setup and retry the mount.
229 
230     if (rc && errno == ENOTBLK) {
231       char *losetup[] = {"losetup", "-fs", dev, 0};
232       int pipe, len;
233       pid_t pid;
234 
235       if (flags & MS_RDONLY) losetup[1] = "-fsr";
236       pid = xpopen(losetup, &pipe, 1);
237       len = readall(pipe, toybuf, sizeof(toybuf)-1);
238       rc = xpclose(pid, pipe);
239       if (!rc && len > 1) {
240         if (toybuf[len-1] == '\n') --len;
241         toybuf[len] = 0;
242         dev = toybuf;
243 
244         continue;
245       }
246       error_msg("losetup failed %d", rc);
247 
248       break;
249     }
250 
251     free(buf);
252     buf = 0;
253     if (!rc) break;
254     if (fp && (errno == EINVAL || errno == EBUSY)) continue;
255 
256     perror_msg("'%s'->'%s'", dev, dir);
257 
258     break;
259   }
260   if (fp) fclose(fp);
261 }
262 
mount_main(void)263 void mount_main(void)
264 {
265   char *opts = 0, *dev = 0, *dir = 0, **ss;
266   long flags = MS_SILENT;
267   struct arg_list *o;
268   struct mtab_list *mtl, *mtl2 = 0, *mm, *remount;
269 
270 // TODO
271 // remount
272 //   - overmounts
273 // shared subtree
274 // -o parsed after fstab options
275 // test if mountpoint already exists (-o noremount?)
276 
277   // First pass; just accumulate string, don't parse flags yet. (This is so
278   // we can modify fstab entries with -a, or mtab with remount.)
279   for (o = TT.optlist; o; o = o->next) comma_collate(&opts, o->arg);
280   if (toys.optflags & FLAG_r) comma_collate(&opts, "ro");
281   if (toys.optflags & FLAG_w) comma_collate(&opts, "rw");
282 
283   // Treat each --option as -o option
284   for (ss = toys.optargs; *ss; ss++) {
285     char *sss = *ss;
286 
287     // If you realy, really want to mount a file named "--", we support it.
288     if (sss[0]=='-' && sss[1]=='-' && sss[2]) comma_collate(&opts, sss+2);
289     else if (!dev) dev = sss;
290     else if (!dir) dir = sss;
291     // same message as lib/args.c ">2" which we can't use because --opts count
292     else error_exit("Max 2 arguments\n");
293   }
294 
295   if ((toys.optflags & FLAG_a) && dir) error_exit("-a with >1 arg");
296 
297   // For remount we need _last_ match (in case of overmounts), so traverse
298   // in reverse order. (Yes I'm using remount as a boolean for a bit here,
299   // the double cast is to get gcc to shut up about it.)
300   remount = (void *)(long)comma_scan(opts, "remount", 1);
301   if (((toys.optflags & FLAG_a) && !access("/proc/mounts", R_OK)) || remount) {
302     mm = dlist_terminate(mtl = mtl2 = xgetmountlist(0));
303     if (remount) remount = mm;
304   }
305 
306   // Do we need to do an /etc/fstab trawl?
307   // This covers -a, -o remount, one argument, all user mounts
308   if ((toys.optflags & FLAG_a) || (dev && (!dir || getuid() || remount))) {
309     if (!remount) dlist_terminate(mtl = xgetmountlist("/etc/fstab"));
310 
311     for (mm = remount ? remount : mtl; mm; mm = (remount ? mm->prev : mm->next))
312     {
313       char *aopts = 0;
314       struct mtab_list *mmm = 0;
315       int aflags, noauto, len;
316 
317       // Check for noauto and get it out of the option list. (Unknown options
318       // that make it to the kernel give filesystem drivers indigestion.)
319       noauto = comma_scan(mm->opts, "noauto", 1);
320 
321       if (toys.optflags & FLAG_a) {
322         // "mount -a /path" to mount all entries under /path
323         if (dev) {
324            len = strlen(dev);
325            if (strncmp(dev, mm->dir, len)
326                || (mm->dir[len] && mm->dir[len] != '/')) continue;
327         } else if (noauto) continue; // never present in the remount case
328         if (!mountlist_istype(mm,TT.type) || !comma_scanall(mm->opts,TT.bigO))
329           continue;
330       } else {
331         if (dir && strcmp(dir, mm->dir)) continue;
332         if (dev && strcmp(dev, mm->device) && (dir || strcmp(dev, mm->dir)))
333           continue;
334       }
335 
336       // Don't overmount the same dev on the same directory
337       // (Unless root explicitly says to in non -a mode.)
338       if (mtl2 && !remount)
339         for (mmm = mtl2; mmm; mmm = mmm->next)
340           if (!strcmp(mm->dir, mmm->dir) && !strcmp(mm->device, mmm->device))
341             break;
342 
343       // user only counts from fstab, not opts.
344       if (!mmm) {
345         TT.okuser = comma_scan(mm->opts, "user", 1);
346         aflags = flag_opts(mm->opts, flags, &aopts);
347         aflags = flag_opts(opts, aflags, &aopts);
348 
349         mount_filesystem(mm->device, mm->dir, mm->type, aflags, aopts);
350       } // TODO else if (getuid()) error_msg("already there") ?
351       free(aopts);
352 
353       if (!(toys.optflags & FLAG_a)) break;
354     }
355     if (CFG_TOYBOX_FREE) {
356       llist_traverse(mtl, free);
357       llist_traverse(mtl2, free);
358     }
359     if (!mm && !(toys.optflags & FLAG_a))
360       error_exit("'%s' not in %s", dir ? dir : dev,
361                  remount ? "/proc/mounts" : "fstab");
362 
363   // show mounts from /proc/mounts
364   } else if (!dev) {
365     for (mtl = xgetmountlist(0); mtl && (mm = dlist_pop(&mtl)); free(mm)) {
366       char *s = 0;
367 
368       if (TT.type && strcmp(TT.type, mm->type)) continue;
369       if (*mm->device == '/') s = xabspath(mm->device, 0);
370       xprintf("%s on %s type %s (%s)\n",
371               s ? s : mm->device, mm->dir, mm->type, mm->opts);
372       free(s);
373     }
374 
375   // two arguments
376   } else {
377     char *more = 0;
378 
379     flags = flag_opts(opts, flags, &more);
380     mount_filesystem(dev, dir, TT.type, flags, more);
381     if (CFG_TOYBOX_FREE) free(more);
382   }
383 }
384