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