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