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