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