Add shared subtree support, suggested by Vladimir Dronnikov. Also break out a
[oweals/busybox.git] / util-linux / mount.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini mount implementation for busybox
4  *
5  * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
6  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7  * Copyright (C) 2005-2006 by Rob Landley <rob@landley.net>
8  *
9  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
10  */
11
12 /* todo:
13  * bb_getopt_ulflags();
14  */
15
16 /* Design notes: There is no spec for mount.  Remind me to write one.
17
18    mount_main() calls singlemount() which calls mount_it_now().
19
20    mount_main() can loop through /etc/fstab for mount -a
21    singlemount() can loop through /etc/filesystems for fstype detection.
22    mount_it_now() does the actual mount.
23 */
24
25 #include "busybox.h"
26 #include <mntent.h>
27
28 // Not real flags, but we want to be able to check for this.
29 #define MOUNT_NOAUTO    (1<<29)
30 #define MOUNT_SWAP      (1<<30)
31 /* Standard mount options (from -o options or --options), with corresponding
32  * flags */
33
34 struct {
35         char *name;
36         long flags;
37 } static mount_options[] = {
38         // MS_FLAGS set a bit.  ~MS_FLAGS disable that bit.  0 flags are NOPs.
39
40         USE_FEATURE_MOUNT_LOOP(
41                 {"loop", 0},
42         )
43
44         USE_FEATURE_MOUNT_FSTAB(
45                 {"defaults", 0},
46                 {"quiet", 0},
47                 {"noauto",MOUNT_NOAUTO},
48                 {"swap",MOUNT_SWAP},
49         )
50
51         USE_FEATURE_MOUNT_FLAGS(
52                 // vfs flags
53                 {"nosuid", MS_NOSUID},
54                 {"suid", ~MS_NOSUID},
55                 {"dev", ~MS_NODEV},
56                 {"nodev", MS_NODEV},
57                 {"exec", ~MS_NOEXEC},
58                 {"noexec", MS_NOEXEC},
59                 {"sync", MS_SYNCHRONOUS},
60                 {"async", ~MS_SYNCHRONOUS},
61                 {"atime", ~MS_NOATIME},
62                 {"noatime", MS_NOATIME},
63                 {"diratime", ~MS_NODIRATIME},
64                 {"nodiratime", MS_NODIRATIME},
65                 {"loud", ~MS_SILENT},
66
67                 // action flags
68
69                 {"bind", MS_BIND},
70                 {"move", MS_MOVE},
71                 {"shared", MS_SHARED},
72                 {"slave", MS_SLAVE},
73                 {"private", MS_PRIVATE},
74                 {"unbindable", MS_UNBINDABLE},
75                 {"rshared", MS_SHARED|MS_RECURSIVE},
76                 {"rslave", MS_SLAVE|MS_RECURSIVE},
77                 {"rprivate", MS_SLAVE|MS_RECURSIVE},
78                 {"runbindable", MS_UNBINDABLE|MS_RECURSIVE},
79         )
80
81         // Always understood.
82
83         {"ro", MS_RDONLY},        // vfs flag
84         {"rw", ~MS_RDONLY},       // vfs flag
85         {"remount", MS_REMOUNT},  // action flag
86
87
88 };
89
90 /* Append mount options to string */
91 static void append_mount_options(char **oldopts, char *newopts)
92 {
93         if(*oldopts && **oldopts) {
94                 char *temp=xasprintf("%s,%s",*oldopts,newopts);
95                 free(*oldopts);
96                 *oldopts=temp;
97         } else {
98                 if (ENABLE_FEATURE_CLEAN_UP) free(*oldopts);
99                 *oldopts = xstrdup(newopts);
100         }
101 }
102
103 /* Use the mount_options list to parse options into flags.
104  * Return list of unrecognized options in *strflags if strflags!=NULL */
105 static int parse_mount_options(char *options, char **unrecognized)
106 {
107         int flags = MS_SILENT;
108
109         // Loop through options
110         for (;;) {
111                 int i;
112                 char *comma = strchr(options, ',');
113
114                 if (comma) *comma = 0;
115
116                 // Find this option in mount_options
117                 for (i = 0; i < (sizeof(mount_options) / sizeof(*mount_options)); i++) {
118                         if (!strcasecmp(mount_options[i].name, options)) {
119                                 long fl = mount_options[i].flags;
120                                 if(fl < 0) flags &= fl;
121                                 else flags |= fl;
122                                 break;
123                         }
124                 }
125                 // If unrecognized not NULL, append unrecognized mount options */
126                 if (unrecognized
127                                 && i == (sizeof(mount_options) / sizeof(*mount_options)))
128                 {
129                         // Add it to strflags, to pass on to kernel
130                         i = *unrecognized ? strlen(*unrecognized) : 0;
131                         *unrecognized = xrealloc(*unrecognized, i+strlen(options)+2);
132
133                         // Comma separated if it's not the first one
134                         if (i) (*unrecognized)[i++] = ',';
135                         strcpy((*unrecognized)+i, options);
136                 }
137
138                 // Advance to next option, or finish
139                 if(comma) {
140                         *comma = ',';
141                         options = ++comma;
142                 } else break;
143         }
144
145         return flags;
146 }
147
148 // Return a list of all block device backed filesystems
149
150 static llist_t *get_block_backed_filesystems(void)
151 {
152         char *fs, *buf,
153                  *filesystems[] = {"/etc/filesystems", "/proc/filesystems", 0};
154         llist_t *list = 0;
155         int i;
156         FILE *f;
157
158         for(i = 0; filesystems[i]; i++) {
159                 if(!(f = fopen(filesystems[i], "r"))) continue;
160
161                 for(fs = buf = 0; (fs = buf = bb_get_chomped_line_from_file(f));
162                         free(buf))
163                 {
164                         if(!strncmp(buf,"nodev",5) && isspace(buf[5])) continue;
165
166                         while(isspace(*fs)) fs++;
167                         if(*fs=='#' || *fs=='*') continue;
168                         if(!*fs) continue;
169
170                         llist_add_to_end(&list,xstrdup(fs));
171                 }
172                 if (ENABLE_FEATURE_CLEAN_UP) fclose(f);
173         }
174
175         return list;
176 }
177
178 llist_t *fslist = 0;
179
180 #if ENABLE_FEATURE_CLEAN_UP
181 static void delete_block_backed_filesystems(void)
182 {
183         llist_free(fslist, free);
184 }
185 #else
186 void delete_block_backed_filesystems(void);
187 #endif
188
189 #if ENABLE_FEATURE_MTAB_SUPPORT
190 static int useMtab;
191 static int fakeIt;
192 #else
193 #define useMtab 0
194 #define fakeIt 0
195 #endif
196
197 // Perform actual mount of specific filesystem at specific location.
198
199 static int mount_it_now(struct mntent *mp, int vfsflags, char *filteropts)
200 {
201         int rc;
202
203         if (fakeIt) { return 0; }
204
205         // Mount, with fallback to read-only if necessary.
206
207         for(;;) {
208                 rc = mount(mp->mnt_fsname, mp->mnt_dir, mp->mnt_type,
209                                 vfsflags, filteropts);
210                 if(!rc || (vfsflags&MS_RDONLY) || (errno!=EACCES && errno!=EROFS))
211                         break;
212                 bb_error_msg("%s is write-protected, mounting read-only",
213                                 mp->mnt_fsname);
214                 vfsflags |= MS_RDONLY;
215         }
216
217         // Abort entirely if permission denied.
218
219         if (rc && errno == EPERM)
220                 bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
221
222         /* If the mount was successful, and we're maintaining an old-style
223          * mtab file by hand, add the new entry to it now. */
224
225         if(ENABLE_FEATURE_MTAB_SUPPORT && useMtab && !rc) {
226                 FILE *mountTable = setmntent(bb_path_mtab_file, "a+");
227                 int i;
228
229                 if(!mountTable)
230                         bb_error_msg("No %s\n",bb_path_mtab_file);
231
232                 // Add vfs string flags
233
234                 for(i=0; mount_options[i].flags != MS_REMOUNT; i++)
235                         if (mount_options[i].flags > 0)
236 // Shut up about the darn const.  It's not important.  I don't care.  (char *)
237                                 append_mount_options(&(mp->mnt_opts), mount_options[i].name);
238
239                 // Remove trailing / (if any) from directory we mounted on
240
241                 i = strlen(mp->mnt_dir);
242                 if(i>1 && mp->mnt_dir[i-1] == '/') mp->mnt_dir[i-1] = 0;
243
244                 // Write and close.
245
246                 if(!mp->mnt_type || !*mp->mnt_type) mp->mnt_type="--bind";
247                 addmntent(mountTable, mp);
248                 endmntent(mountTable);
249                 if (ENABLE_FEATURE_CLEAN_UP)
250                         if(strcmp(mp->mnt_type,"--bind")) mp->mnt_type = 0;
251         }
252
253         return rc;
254 }
255
256
257 // Mount one directory.  Handles NFS, loopback, autobind, and filesystem type
258 // detection.  Returns 0 for success, nonzero for failure.
259
260 static int singlemount(struct mntent *mp, int ignore_busy)
261 {
262         int rc = -1, vfsflags;
263         char *loopFile = 0, *filteropts = 0;
264         llist_t *fl = 0;
265         struct stat st;
266
267         vfsflags = parse_mount_options(mp->mnt_opts, &filteropts);
268
269         // Treat fstype "auto" as unspecified.
270
271         if (mp->mnt_type && !strcmp(mp->mnt_type,"auto")) mp->mnt_type = 0;
272
273         // Might this be an NFS filesystem?
274
275         if (ENABLE_FEATURE_MOUNT_NFS &&
276                 (!mp->mnt_type || !strcmp(mp->mnt_type,"nfs")) &&
277                 strchr(mp->mnt_fsname, ':') != NULL)
278         {
279                 if (nfsmount(mp->mnt_fsname, mp->mnt_dir, &vfsflags, &filteropts, 1)) {
280                         bb_perror_msg("nfsmount failed");
281                         goto report_error;
282                 } else {
283                         // Strangely enough, nfsmount() doesn't actually mount() anything.
284                         mp->mnt_type = "nfs";
285                         rc = mount_it_now(mp, vfsflags, filteropts);
286                         if (ENABLE_FEATURE_CLEAN_UP) free(filteropts);
287                         
288                         goto report_error;
289                 }
290         }
291
292         // Look at the file.  (Not found isn't a failure for remount, or for
293         // a synthetic filesystem like proc or sysfs.)
294
295         if (!lstat(mp->mnt_fsname, &st) && !(vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE | MS_SHARED | MS_PRIVATE || MS_SLAVE | MS_UNBINDABLE)))
296         {
297                 // Do we need to allocate a loopback device for it?
298
299                 if (ENABLE_FEATURE_MOUNT_LOOP && S_ISREG(st.st_mode)) {
300                         loopFile = bb_simplify_path(mp->mnt_fsname);
301                         mp->mnt_fsname = 0;
302                         switch(set_loop(&(mp->mnt_fsname), loopFile, 0)) {
303                                 case 0:
304                                 case 1:
305                                         break;
306                                 default:
307                                         bb_error_msg( errno == EPERM || errno == EACCES
308                                                 ? bb_msg_perm_denied_are_you_root
309                                                 : "Couldn't setup loop device");
310                                         return errno;
311                         }
312
313                 // Autodetect bind mounts
314
315                 } else if (S_ISDIR(st.st_mode) && !mp->mnt_type) vfsflags |= MS_BIND;
316         }
317
318         /* If we know the fstype (or don't need to), jump straight
319          * to the actual mount. */
320
321         if (mp->mnt_type || (vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE)))
322                 rc = mount_it_now(mp, vfsflags, filteropts);
323
324         // Loop through filesystem types until mount succeeds or we run out
325
326         else {
327
328                 /* Initialize list of block backed filesystems.  This has to be
329                  * done here so that during "mount -a", mounts after /proc shows up
330                  * can autodetect. */
331
332                 if (!fslist) {
333                         fslist = get_block_backed_filesystems();
334                         if (ENABLE_FEATURE_CLEAN_UP && fslist)
335                                 atexit(delete_block_backed_filesystems);
336                 }
337
338                 for (fl = fslist; fl; fl = fl->link) {
339                         mp->mnt_type = fl->data;
340
341                         if (!(rc = mount_it_now(mp,vfsflags, filteropts))) break;
342
343                         mp->mnt_type = 0;
344                 }
345         }
346
347         if (ENABLE_FEATURE_CLEAN_UP) free(filteropts);
348
349         // If mount failed, clean up loop file (if any).
350
351         if (ENABLE_FEATURE_MOUNT_LOOP && rc && loopFile) {
352                 del_loop(mp->mnt_fsname);
353                 if (ENABLE_FEATURE_CLEAN_UP) {
354                         free(loopFile);
355                         free(mp->mnt_fsname);
356                 }
357         }
358 report_error:
359         if (rc && errno == EBUSY && ignore_busy) rc = 0;
360         if (rc < 0)
361                 bb_perror_msg("Mounting %s on %s failed", mp->mnt_fsname, mp->mnt_dir);
362
363         return rc;
364 }
365
366 // Parse options, if necessary parse fstab/mtab, and call singlemount for
367 // each directory to be mounted.
368
369 int mount_main(int argc, char **argv)
370 {
371         char *cmdopts = xstrdup(""), *fstabname, *fstype=0, *storage_path=0;
372         FILE *fstab;
373         int i, opt, all = FALSE, rc = 0;
374         struct mntent mtpair[2], *mtcur = mtpair;
375
376         /* parse long options, like --bind and --move.  Note that -o option
377          * and --option are synonymous.  Yes, this means --remount,rw works. */
378
379         for (i = opt = 0; i < argc; i++) {
380                 if (argv[i][0] == '-' && argv[i][1] == '-') {
381                         append_mount_options(&cmdopts,argv[i]+2);
382                 } else argv[opt++] = argv[i];
383         }
384         argc = opt;
385
386         // Parse remaining options
387
388         while ((opt = getopt(argc, argv, "o:t:rwavnf")) > 0) {
389                 switch (opt) {
390                         case 'o':
391                                 append_mount_options(&cmdopts, optarg);
392                                 break;
393                         case 't':
394                                 fstype = optarg;
395                                 break;
396                         case 'r':
397                                 append_mount_options(&cmdopts, "ro");
398                                 break;
399                         case 'w':
400                                 append_mount_options(&cmdopts, "rw");
401                                 break;
402                         case 'a':
403                                 all = TRUE;
404                                 break;
405                         case 'n':
406                                 USE_FEATURE_MTAB_SUPPORT(useMtab = FALSE;)
407                                 break;
408                         case 'f':
409                                 USE_FEATURE_MTAB_SUPPORT(fakeIt = FALSE;)
410                                 break;
411                         case 'v':
412                                 break;          // ignore -v
413                         default:
414                                 bb_show_usage();
415                 }
416         }
417
418         // Three or more non-option arguments?  Die with a usage message.
419
420         if (optind-argc>2) bb_show_usage();
421
422         // If we have no arguments, show currently mounted filesystems
423
424         if (optind == argc) {
425                 if (!all) {
426                         FILE *mountTable = setmntent(bb_path_mtab_file, "r");
427
428                         if(!mountTable) bb_error_msg_and_die("No %s",bb_path_mtab_file);
429
430                         while (getmntent_r(mountTable,mtpair,bb_common_bufsiz1,
431                                                                 sizeof(bb_common_bufsiz1)))
432                         {
433                                 // Don't show rootfs.
434                                 if (!strcmp(mtpair->mnt_fsname, "rootfs")) continue;
435
436                                 if (!fstype || !strcmp(mtpair->mnt_type, fstype))
437                                         printf("%s on %s type %s (%s)\n", mtpair->mnt_fsname,
438                                                         mtpair->mnt_dir, mtpair->mnt_type,
439                                                         mtpair->mnt_opts);
440                         }
441                         if (ENABLE_FEATURE_CLEAN_UP) endmntent(mountTable);
442                         return EXIT_SUCCESS;
443                 }
444         }
445
446         // When we have two arguments, the second is the directory and we can
447         // skip looking at fstab entirely.  We can always abspath() the directory
448         // argument when we get it.
449
450         if (optind+2 == argc) {
451                 mtpair->mnt_fsname = argv[optind];
452                 mtpair->mnt_dir = argv[optind+1];
453                 mtpair->mnt_type = fstype;
454                 mtpair->mnt_opts = cmdopts;
455                 rc = singlemount(mtpair, 0);
456                 goto clean_up;
457         }
458
459         // If we have at least one argument, it's the storage location
460
461         if (optind < argc) storage_path = bb_simplify_path(argv[optind]);
462
463         // Open either fstab or mtab
464
465         if (parse_mount_options(cmdopts,0) & MS_REMOUNT)
466                 fstabname = bb_path_mtab_file;  // Again with the evil const (char *).
467         else fstabname="/etc/fstab";
468
469         if (!(fstab=setmntent(fstabname,"r")))
470                 bb_perror_msg_and_die("Cannot read %s",fstabname);
471
472         // Loop through entries until we find what we're looking for.
473
474         memset(mtpair,0,sizeof(mtpair));
475         for (;;) {
476                 struct mntent *mtnext = mtpair + (mtcur==mtpair ? 1 : 0);
477
478                 // Get next fstab entry
479
480                 if (!getmntent_r(fstab, mtcur, bb_common_bufsiz1
481                                         + (mtcur==mtpair ? sizeof(bb_common_bufsiz1)/2 : 0),
482                                 sizeof(bb_common_bufsiz1)/2))
483                 {
484                         // Were we looking for something specific?
485
486                         if (optind != argc) {
487
488                                 // If we didn't find anything, complain.
489
490                                 if (!mtnext->mnt_fsname)
491                                         bb_error_msg_and_die("Can't find %s in %s",
492                                                 argv[optind], fstabname);
493
494                                 // Mount the last thing we found.
495
496                                 mtcur = mtnext;
497                                 mtcur->mnt_opts = xstrdup(mtcur->mnt_opts);
498                                 append_mount_options(&(mtcur->mnt_opts),cmdopts);
499                                 rc = singlemount(mtcur, 0);
500                                 free(mtcur->mnt_opts);
501                         }
502                         goto clean_up;
503                 }
504
505                 /* If we're trying to mount something specific and this isn't it,
506                  * skip it.  Note we must match both the exact text in fstab (ala
507                  * "proc") or a full path from root */
508
509                 if (optind != argc) {
510
511                         // Is this what we're looking for?
512
513                         if(strcmp(argv[optind],mtcur->mnt_fsname) &&
514                            strcmp(storage_path,mtcur->mnt_fsname) &&
515                            strcmp(argv[optind],mtcur->mnt_dir) &&
516                            strcmp(storage_path,mtcur->mnt_dir)) continue;
517
518                         // Remember this entry.  Something later may have overmounted
519                         // it, and we want the _last_ match.
520
521                         mtcur = mtnext;
522
523                 // If we're mounting all.
524
525                 } else {
526
527                         // Do we need to match a filesystem type?
528                         if (fstype && strcmp(mtcur->mnt_type,fstype)) continue;
529
530                         // Skip noauto and swap anyway.
531
532                         if (parse_mount_options(mtcur->mnt_opts,0)
533                                 & (MOUNT_NOAUTO | MOUNT_SWAP)) continue;
534
535                         // Mount this thing.
536
537                         if (singlemount(mtcur, 1)) {
538                                 /* Count number of failed mounts */
539                                 rc++;
540                         }
541                 }
542         }
543         if (ENABLE_FEATURE_CLEAN_UP) endmntent(fstab);
544
545 clean_up:
546
547         if (ENABLE_FEATURE_CLEAN_UP) {
548                 free(storage_path);
549                 free(cmdopts);
550         }
551
552         return rc;
553 }