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