1 /* vi: set sw=4 ts=4: */
3 * Mini mount implementation for busybox
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>
9 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
12 /* Design notes: There is no spec for mount. Remind me to write one.
14 mount_main() calls singlemount() which calls mount_it_now().
16 mount_main() can loop through /etc/fstab for mount -a
17 singlemount() can loop through /etc/filesystems for fstype detection.
18 mount_it_now() does the actual mount.
25 /* Needed for nfs support only... */
26 #include <sys/utsname.h>
30 #include <rpc/pmap_prot.h>
31 #include <rpc/pmap_clnt.h>
34 #define MS_SILENT (1 << 15)
36 /* Grab more as needed from util-linux's mount/mount_constants.h */
38 #define MS_DIRSYNC 128 /* Directory modifications are synchronous */
42 #if defined(__dietlibc__)
43 /* 16.12.2006, Sampo Kellomaki (sampo@iki.fi)
44 * dietlibc-0.30 does not have implementation of getmntent_r() */
45 static struct mntent *getmntent_r(FILE* stream, struct mntent* result, char* buffer, int bufsize)
47 struct mntent* ment = getmntent(stream);
48 memcpy(result, ment, sizeof(struct mntent));
54 // Not real flags, but we want to be able to check for this.
56 MOUNT_USERS = (1<<28)*ENABLE_DESKTOP,
57 MOUNT_NOAUTO = (1<<29),
62 #define OPTION_STR "o:t:rwanfvsi"
76 #if ENABLE_FEATURE_MTAB_SUPPORT
77 #define useMtab (!(option_mask32 & OPT_n))
82 #if ENABLE_FEATURE_MOUNT_FAKE
83 #define fakeIt (option_mask32 & OPT_f)
89 // TODO: more "user" flag compatibility.
90 // "user" option (from mount manpage):
91 // Only the user that mounted a filesystem can unmount it again.
92 // If any user should be able to unmount, then use users instead of user
93 // in the fstab line. The owner option is similar to the user option,
94 // with the restriction that the user must be the owner of the special file.
95 // This may be useful e.g. for /dev/fd if a login script makes
96 // the console user owner of this device.
98 /* Standard mount options (from -o options or --options), with corresponding
101 static const int32_t mount_options[] = {
102 // MS_FLAGS set a bit. ~MS_FLAGS disable that bit. 0 flags are NOPs.
104 USE_FEATURE_MOUNT_LOOP(
108 USE_FEATURE_MOUNT_FSTAB(
110 /* "quiet" 0 - do not filter out, vfat wants to see it */
111 /* "noauto" */ MOUNT_NOAUTO,
112 /* "sw" */ MOUNT_SWAP,
113 /* "swap" */ MOUNT_SWAP,
114 USE_DESKTOP(/* "user" */ MOUNT_USERS,)
115 USE_DESKTOP(/* "users" */ MOUNT_USERS,)
119 USE_FEATURE_MOUNT_FLAGS(
121 /* "nosuid" */ MS_NOSUID,
122 /* "suid" */ ~MS_NOSUID,
123 /* "dev" */ ~MS_NODEV,
124 /* "nodev" */ MS_NODEV,
125 /* "exec" */ ~MS_NOEXEC,
126 /* "noexec" */ MS_NOEXEC,
127 /* "sync" */ MS_SYNCHRONOUS,
128 /* "dirsync" */ MS_DIRSYNC,
129 /* "async" */ ~MS_SYNCHRONOUS,
130 /* "atime" */ ~MS_NOATIME,
131 /* "noatime" */ MS_NOATIME,
132 /* "diratime" */ ~MS_NODIRATIME,
133 /* "nodiratime" */ MS_NODIRATIME,
134 /* "loud" */ ~MS_SILENT,
137 /* "bind" */ MS_BIND,
138 /* "move" */ MS_MOVE,
139 /* "shared" */ MS_SHARED,
140 /* "slave" */ MS_SLAVE,
141 /* "private" */ MS_PRIVATE,
142 /* "unbindable" */ MS_UNBINDABLE,
143 /* "rshared" */ MS_SHARED|MS_RECURSIVE,
144 /* "rslave" */ MS_SLAVE|MS_RECURSIVE,
145 /* "rprivate" */ MS_SLAVE|MS_RECURSIVE,
146 /* "runbindable" */ MS_UNBINDABLE|MS_RECURSIVE,
149 // Always understood.
150 /* "ro" */ MS_RDONLY, // vfs flag
151 /* "rw" */ ~MS_RDONLY, // vfs flag
152 /* "remount" */ MS_REMOUNT // action flag
155 static const char mount_option_str[] =
156 USE_FEATURE_MOUNT_LOOP(
159 USE_FEATURE_MOUNT_FSTAB(
161 /* "quiet" "\0" - do not filter out, vfat wants to see it */
165 USE_DESKTOP("user" "\0")
166 USE_DESKTOP("users" "\0")
169 USE_FEATURE_MOUNT_FLAGS(
199 // Always understood.
200 "ro" "\0" // vfs flag
201 "rw" "\0" // vfs flag
202 "remount" "\0" // action flag
207 #if ENABLE_FEATURE_MOUNT_NFS
208 smalluint nfs_mount_version;
210 #if ENABLE_FEATURE_MOUNT_VERBOSE
214 char getmntent_buf[sizeof(bb_common_bufsiz1) - 8*3];
217 #define G (*(struct globals*)&bb_common_bufsiz1)
218 #define nfs_mount_version (G.nfs_mount_version)
219 #define verbose (G.verbose )
220 #define fslist (G.fslist )
221 #define getmntent_buf (G.getmntent_buf )
224 #if ENABLE_FEATURE_MOUNT_VERBOSE
225 static int verbose_mount(const char *source, const char *target,
226 const char *filesystemtype,
227 unsigned long mountflags, const void *data)
232 rc = mount(source, target, filesystemtype, mountflags, data);
234 bb_perror_msg("mount('%s','%s','%s',0x%08lx,'%s'):%d",
235 source, target, filesystemtype,
236 mountflags, (char*)data, rc);
240 #define verbose_mount(...) mount(__VA_ARGS__)
243 /* Append mount options to string */
244 static void append_mount_options(char **oldopts, const char *newopts)
246 if (*oldopts && **oldopts) {
247 /* do not insert options which are already there */
250 int len = strlen(newopts);
251 p = strchr(newopts, ',');
252 if (p) len = p - newopts;
255 if (!strncmp(p, newopts, len)
256 && (p[len] == ',' || p[len] == '\0'))
262 p = xasprintf("%s,%.*s", *oldopts, len, newopts);
267 while (newopts[0] == ',') newopts++;
270 if (ENABLE_FEATURE_CLEAN_UP) free(*oldopts);
271 *oldopts = xstrdup(newopts);
275 /* Use the mount_options list to parse options into flags.
276 * Also return list of unrecognized options if unrecognized!=NULL */
277 static int parse_mount_options(char *options, char **unrecognized)
279 int flags = MS_SILENT;
281 // Loop through options
284 char *comma = strchr(options, ',');
285 const char *option_str = mount_option_str;
287 if (comma) *comma = '\0';
289 // Find this option in mount_options
290 for (i = 0; i < ARRAY_SIZE(mount_options); i++) {
291 if (!strcasecmp(option_str, options)) {
292 long fl = mount_options[i];
293 if (fl < 0) flags &= fl;
297 option_str += strlen(option_str) + 1;
299 // If unrecognized not NULL, append unrecognized mount options */
300 if (unrecognized && i == ARRAY_SIZE(mount_options)) {
301 // Add it to strflags, to pass on to kernel
302 i = *unrecognized ? strlen(*unrecognized) : 0;
303 *unrecognized = xrealloc(*unrecognized, i+strlen(options)+2);
305 // Comma separated if it's not the first one
306 if (i) (*unrecognized)[i++] = ',';
307 strcpy((*unrecognized)+i, options);
312 // Advance to next option
320 // Return a list of all block device backed filesystems
322 static llist_t *get_block_backed_filesystems(void)
324 static const char filesystems[2][sizeof("/proc/filesystems")] = {
333 for (i = 0; i < 2; i++) {
334 f = fopen(filesystems[i], "r");
337 while ((buf = xmalloc_getline(f)) != 0) {
338 if (!strncmp(buf, "nodev", 5) && isspace(buf[5]))
340 fs = skip_whitespace(buf);
341 if (*fs=='#' || *fs=='*' || !*fs) continue;
343 llist_add_to_end(&list, xstrdup(fs));
346 if (ENABLE_FEATURE_CLEAN_UP) fclose(f);
352 #if ENABLE_FEATURE_CLEAN_UP
353 static void delete_block_backed_filesystems(void)
355 llist_free(fslist, free);
358 void delete_block_backed_filesystems(void);
361 // Perform actual mount of specific filesystem at specific location.
362 // NB: mp->xxx fields may be trashed on exit
363 static int mount_it_now(struct mntent *mp, int vfsflags, char *filteropts)
367 if (fakeIt) goto mtab;
369 // Mount, with fallback to read-only if necessary.
372 rc = verbose_mount(mp->mnt_fsname, mp->mnt_dir, mp->mnt_type,
373 vfsflags, filteropts);
375 // If mount failed, try
376 // helper program <mnt_type>
377 if (ENABLE_FEATURE_MOUNT_HELPERS && rc) {
379 int errno_save = errno;
380 args[0] = mp->mnt_type;
383 args[rc++] = (char *)"-o";
384 args[rc++] = filteropts;
386 args[rc++] = mp->mnt_fsname;
387 args[rc++] = mp->mnt_dir;
389 rc = wait4pid(spawn(args));
395 if (!rc || (vfsflags & MS_RDONLY) || (errno != EACCES && errno != EROFS))
397 if (!(vfsflags & MS_SILENT))
398 bb_error_msg("%s is write-protected, mounting read-only",
400 vfsflags |= MS_RDONLY;
403 // Abort entirely if permission denied.
405 if (rc && errno == EPERM)
406 bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
408 /* If the mount was successful, and we're maintaining an old-style
409 * mtab file by hand, add the new entry to it now. */
411 if (useMtab && !rc && !(vfsflags & MS_REMOUNT)) {
413 FILE *mountTable = setmntent(bb_path_mtab_file, "a+");
414 const char *option_str = mount_option_str;
418 bb_error_msg("no %s", bb_path_mtab_file);
422 // Add vfs string flags
424 for (i = 0; mount_options[i] != MS_REMOUNT; i++) {
425 if (mount_options[i] > 0 && (mount_options[i] & vfsflags))
426 append_mount_options(&(mp->mnt_opts), option_str);
427 option_str += strlen(option_str) + 1;
430 // Remove trailing / (if any) from directory we mounted on
432 i = strlen(mp->mnt_dir) - 1;
433 if (i > 0 && mp->mnt_dir[i] == '/') mp->mnt_dir[i] = '\0';
435 // Convert to canonical pathnames as needed
437 mp->mnt_dir = bb_simplify_path(mp->mnt_dir);
439 if (!mp->mnt_type || !*mp->mnt_type) { /* bind mount */
440 mp->mnt_fsname = fsname = bb_simplify_path(mp->mnt_fsname);
441 mp->mnt_type = (char*)"bind";
443 mp->mnt_freq = mp->mnt_passno = 0;
447 addmntent(mountTable, mp);
448 endmntent(mountTable);
449 if (ENABLE_FEATURE_CLEAN_UP) {
458 #if ENABLE_FEATURE_MOUNT_NFS
462 * Copyright (C) 1993 Rick Sladkey <jrs@world.std.com>
464 * Licensed under GPLv2, see file LICENSE in this tarball for details.
466 * Wed Feb 8 12:51:48 1995, biro@yggdrasil.com (Ross Biro): allow all port
467 * numbers to be specified on the command line.
469 * Fri, 8 Mar 1996 18:01:39, Swen Thuemmler <swen@uni-paderborn.de>:
470 * Omit the call to connect() for Linux version 1.3.11 or later.
472 * Wed Oct 1 23:55:28 1997: Dick Streefland <dick_streefland@tasking.com>
473 * Implemented the "bg", "fg" and "retry" mount options for NFS.
475 * 1999-02-22 Arkadiusz Mi¶kiewicz <misiek@misiek.eu.org>
476 * - added Native Language Support
478 * Modified by Olaf Kirch and Trond Myklebust for new NFS code,
482 /* This is just a warning of a common mistake. Possibly this should be a
483 * uclibc faq entry rather than in busybox... */
484 #if defined(__UCLIBC__) && ! defined(__UCLIBC_HAS_RPC__)
485 #error "You need to build uClibc with UCLIBC_HAS_RPC for NFS support."
488 #define MOUNTPORT 635
489 #define MNTPATHLEN 1024
490 #define MNTNAMLEN 255
494 typedef char fhandle[FHSIZE];
497 unsigned int fhandle3_len;
509 MNT3ERR_NAMETOOLONG = 63,
510 MNT3ERR_NOTSUPP = 10004,
511 MNT3ERR_SERVERFAULT = 10006,
513 typedef enum mountstat3 mountstat3;
516 unsigned int fhs_status;
521 typedef struct fhstatus fhstatus;
523 struct mountres3_ok {
526 unsigned int auth_flavours_len;
527 char *auth_flavours_val;
530 typedef struct mountres3_ok mountres3_ok;
533 mountstat3 fhs_status;
535 mountres3_ok mountinfo;
538 typedef struct mountres3 mountres3;
540 typedef char *dirpath;
544 typedef struct mountbody *mountlist;
548 dirpath ml_directory;
551 typedef struct mountbody mountbody;
553 typedef struct groupnode *groups;
559 typedef struct groupnode groupnode;
561 typedef struct exportnode *exports;
568 typedef struct exportnode exportnode;
581 typedef struct ppathcnf ppathcnf;
583 #define MOUNTPROG 100005
586 #define MOUNTPROC_NULL 0
587 #define MOUNTPROC_MNT 1
588 #define MOUNTPROC_DUMP 2
589 #define MOUNTPROC_UMNT 3
590 #define MOUNTPROC_UMNTALL 4
591 #define MOUNTPROC_EXPORT 5
592 #define MOUNTPROC_EXPORTALL 6
594 #define MOUNTVERS_POSIX 2
596 #define MOUNTPROC_PATHCONF 7
600 #define MOUNTPROC3_NULL 0
601 #define MOUNTPROC3_MNT 1
602 #define MOUNTPROC3_DUMP 2
603 #define MOUNTPROC3_UMNT 3
604 #define MOUNTPROC3_UMNTALL 4
605 #define MOUNTPROC3_EXPORT 5
617 * We want to be able to compile mount on old kernels in such a way
618 * that the binary will work well on more recent kernels.
619 * Thus, if necessary we teach nfsmount.c the structure of new fields
620 * that will come later.
622 * Moreover, the new kernel includes conflict with glibc includes
623 * so it is easiest to ignore the kernel altogether (at compile time).
631 unsigned char data[64];
634 struct nfs_mount_data {
637 struct nfs2_fh old_root; /* 1 */
643 int acregmin; /* 1 */
644 int acregmax; /* 1 */
645 int acdirmin; /* 1 */
646 int acdirmax; /* 1 */
647 struct sockaddr_in addr; /* 1 */
648 char hostname[256]; /* 1 */
650 unsigned int bsize; /* 3 */
651 struct nfs3_fh root; /* 4 */
654 /* bits in the flags field */
656 NFS_MOUNT_SOFT = 0x0001, /* 1 */
657 NFS_MOUNT_INTR = 0x0002, /* 1 */
658 NFS_MOUNT_SECURE = 0x0004, /* 1 */
659 NFS_MOUNT_POSIX = 0x0008, /* 1 */
660 NFS_MOUNT_NOCTO = 0x0010, /* 1 */
661 NFS_MOUNT_NOAC = 0x0020, /* 1 */
662 NFS_MOUNT_TCP = 0x0040, /* 2 */
663 NFS_MOUNT_VER3 = 0x0080, /* 3 */
664 NFS_MOUNT_KERBEROS = 0x0100, /* 3 */
665 NFS_MOUNT_NONLM = 0x0200 /* 3 */
670 * We need to translate between nfs status return values and
671 * the local errno values which may not be the same.
673 * Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>: change errno:
674 * "after #include <errno.h> the symbol errno is reserved for any use,
675 * it cannot even be used as a struct tag or field name".
679 #define EDQUOT ENOSPC
682 // Convert each NFSERR_BLAH into EBLAH
684 static const struct {
688 {0,0}, {1,EPERM}, {2,ENOENT}, {5,EIO}, {6,ENXIO}, {13,EACCES}, {17,EEXIST},
689 {19,ENODEV}, {20,ENOTDIR}, {21,EISDIR}, {22,EINVAL}, {27,EFBIG},
690 {28,ENOSPC}, {30,EROFS}, {63,ENAMETOOLONG}, {66,ENOTEMPTY}, {69,EDQUOT},
691 {70,ESTALE}, {71,EREMOTE}, {-1,EIO}
694 static char *nfs_strerror(int status)
698 for (i = 0; nfs_errtbl[i].stat != -1; i++) {
699 if (nfs_errtbl[i].stat == status)
700 return strerror(nfs_errtbl[i].errnum);
702 return xasprintf("unknown nfs status return value: %d", status);
705 static bool_t xdr_fhandle(XDR *xdrs, fhandle objp)
707 if (!xdr_opaque(xdrs, objp, FHSIZE))
712 static bool_t xdr_fhstatus(XDR *xdrs, fhstatus *objp)
714 if (!xdr_u_int(xdrs, &objp->fhs_status))
716 switch (objp->fhs_status) {
718 if (!xdr_fhandle(xdrs, objp->fhstatus_u.fhs_fhandle))
727 static bool_t xdr_dirpath(XDR *xdrs, dirpath *objp)
729 if (!xdr_string(xdrs, objp, MNTPATHLEN))
734 static bool_t xdr_fhandle3(XDR *xdrs, fhandle3 *objp)
736 if (!xdr_bytes(xdrs, (char **)&objp->fhandle3_val, (unsigned int *) &objp->fhandle3_len, FHSIZE3))
741 static bool_t xdr_mountres3_ok(XDR *xdrs, mountres3_ok *objp)
743 if (!xdr_fhandle3(xdrs, &objp->fhandle))
745 if (!xdr_array(xdrs, &(objp->auth_flavours.auth_flavours_val), &(objp->auth_flavours.auth_flavours_len), ~0,
746 sizeof (int), (xdrproc_t) xdr_int))
751 static bool_t xdr_mountstat3(XDR *xdrs, mountstat3 *objp)
753 if (!xdr_enum(xdrs, (enum_t *) objp))
758 static bool_t xdr_mountres3(XDR *xdrs, mountres3 *objp)
760 if (!xdr_mountstat3(xdrs, &objp->fhs_status))
762 switch (objp->fhs_status) {
764 if (!xdr_mountres3_ok(xdrs, &objp->mountres3_u.mountinfo))
773 #define MAX_NFSPROT ((nfs_mount_version >= 4) ? 3 : 2)
776 * Unfortunately, the kernel prints annoying console messages
777 * in case of an unexpected nfs mount version (instead of
778 * just returning some error). Therefore we'll have to try
779 * and figure out what version the kernel expects.
782 * KERNEL_NFS_MOUNT_VERSION: kernel sources at compile time
783 * NFS_MOUNT_VERSION: these nfsmount sources at compile time
784 * nfs_mount_version: version this source and running kernel can handle
787 find_kernel_nfs_mount_version(void)
791 if (nfs_mount_version)
794 nfs_mount_version = 4; /* default */
796 kernel_version = get_linux_version_code();
797 if (kernel_version) {
798 if (kernel_version < KERNEL_VERSION(2,1,32))
799 nfs_mount_version = 1;
800 else if (kernel_version < KERNEL_VERSION(2,2,18) ||
801 (kernel_version >= KERNEL_VERSION(2,3,0) &&
802 kernel_version < KERNEL_VERSION(2,3,99)))
803 nfs_mount_version = 3;
804 /* else v4 since 2.3.99pre4 */
809 get_mountport(struct pmap *pm_mnt,
810 struct sockaddr_in *server_addr,
812 long unsigned version,
816 struct pmaplist *pmap;
818 server_addr->sin_port = PMAPPORT;
819 /* glibc 2.4 (still) has pmap_getmaps(struct sockaddr_in *).
820 * I understand it like "IPv6 for this is not 100% ready" */
821 pmap = pmap_getmaps(server_addr);
823 if (version > MAX_NFSPROT)
824 version = MAX_NFSPROT;
827 pm_mnt->pm_prog = prog;
828 pm_mnt->pm_vers = version;
829 pm_mnt->pm_prot = proto;
830 pm_mnt->pm_port = port;
833 if (pmap->pml_map.pm_prog != prog)
835 if (!version && pm_mnt->pm_vers > pmap->pml_map.pm_vers)
837 if (version > 2 && pmap->pml_map.pm_vers != version)
839 if (version && version <= 2 && pmap->pml_map.pm_vers > 2)
841 if (pmap->pml_map.pm_vers > MAX_NFSPROT ||
842 (proto && pm_mnt->pm_prot && pmap->pml_map.pm_prot != proto) ||
843 (port && pmap->pml_map.pm_port != port))
845 memcpy(pm_mnt, &pmap->pml_map, sizeof(*pm_mnt));
847 pmap = pmap->pml_next;
849 if (!pm_mnt->pm_vers)
850 pm_mnt->pm_vers = MOUNTVERS;
851 if (!pm_mnt->pm_port)
852 pm_mnt->pm_port = MOUNTPORT;
853 if (!pm_mnt->pm_prot)
854 pm_mnt->pm_prot = IPPROTO_TCP;
858 static int daemonize(void)
862 if (pid < 0) /* error */
864 if (pid > 0) /* parent */
867 fd = xopen(bb_dev_null, O_RDWR);
871 while (fd > 2) close(fd--);
873 openlog(applet_name, LOG_PID, LOG_DAEMON);
874 logmode = LOGMODE_SYSLOG;
878 static inline int daemonize(void) { return -ENOSYS; }
882 static inline int we_saw_this_host_before(const char *hostname)
887 /* RPC strerror analogs are terminally idiotic:
888 * *mandatory* prefix and \n at end.
889 * This hopefully helps. Usage:
890 * error_msg_rpc(clnt_*error*(" ")) */
891 static void error_msg_rpc(const char *msg)
894 while (msg[0] == ' ' || msg[0] == ':') msg++;
896 while (len && msg[len-1] == '\n') len--;
897 bb_error_msg("%.*s", len, msg);
900 // NB: mp->xxx fields may be trashed on exit
901 static int nfsmount(struct mntent *mp, int vfsflags, char *filteropts)
907 struct nfs_mount_data data;
910 struct sockaddr_in server_addr;
911 struct sockaddr_in mount_server_addr;
914 struct fhstatus nfsv2;
915 struct mountres3 nfsv3;
941 find_kernel_nfs_mount_version();
949 /* NB: hostname, mounthost, filteropts must be free()d prior to return */
951 filteropts = xstrdup(filteropts); /* going to trash it later... */
953 hostname = xstrdup(mp->mnt_fsname);
954 /* mount_main() guarantees that ':' is there */
955 s = strchr(hostname, ':');
958 /* Ignore all but first hostname in replicated mounts
959 until they can be fully supported. (mack@sgi.com) */
960 s = strchr(hostname, ',');
963 bb_error_msg("warning: multiple hostnames not supported");
966 server_addr.sin_family = AF_INET;
967 if (!inet_aton(hostname, &server_addr.sin_addr)) {
968 hp = gethostbyname(hostname);
970 bb_herror_msg("%s", hostname);
973 if (hp->h_length > sizeof(struct in_addr)) {
974 bb_error_msg("got bad hp->h_length");
975 hp->h_length = sizeof(struct in_addr);
977 memcpy(&server_addr.sin_addr,
978 hp->h_addr, hp->h_length);
981 memcpy(&mount_server_addr, &server_addr, sizeof(mount_server_addr));
983 /* add IP address to mtab options for use when unmounting */
985 if (!mp->mnt_opts) { /* TODO: actually mp->mnt_opts is never NULL */
986 mp->mnt_opts = xasprintf("addr=%s", inet_ntoa(server_addr.sin_addr));
988 char *tmp = xasprintf("%s%saddr=%s", mp->mnt_opts,
989 mp->mnt_opts[0] ? "," : "",
990 inet_ntoa(server_addr.sin_addr));
995 /* Set default options.
996 * rsize/wsize (and bsize, for ver >= 3) are left 0 in order to
997 * let the kernel decide.
998 * timeo is filled in after we know whether it'll be TCP or UDP. */
999 memset(&data, 0, sizeof(data));
1005 data.namlen = NAME_MAX;
1013 retry = 10000; /* 10000 minutes ~ 1 week */
1016 mountprog = MOUNTPROG;
1024 if (filteropts) for (opt = strtok(filteropts, ","); opt; opt = strtok(NULL, ",")) {
1025 char *opteq = strchr(opt, '=');
1027 static const char options[] ALIGN1 =
1032 /* 4 */ "acregmin\0"
1033 /* 5 */ "acregmax\0"
1034 /* 6 */ "acdirmin\0"
1035 /* 7 */ "acdirmax\0"
1039 /* 11 */ "mountport\0"
1040 /* 12 */ "mounthost\0"
1041 /* 13 */ "mountprog\0"
1042 /* 14 */ "mountvers\0"
1043 /* 15 */ "nfsprog\0"
1044 /* 16 */ "nfsvers\0"
1049 int val = xatoi_u(opteq + 1);
1051 switch (index_in_strings(options, opt)) {
1061 case 3: // "retrans"
1064 case 4: // "acregmin"
1065 data.acregmin = val;
1067 case 5: // "acregmax"
1068 data.acregmax = val;
1070 case 6: // "acdirmin"
1071 data.acdirmin = val;
1073 case 7: // "acdirmax"
1074 data.acdirmax = val;
1076 case 8: // "actimeo"
1077 data.acregmin = val;
1078 data.acregmax = val;
1079 data.acdirmin = val;
1080 data.acdirmax = val;
1088 case 11: // "mountport"
1091 case 12: // "mounthost"
1092 mounthost = xstrndup(opteq+1,
1093 strcspn(opteq+1," \t\n\r,"));
1095 case 13: // "mountprog"
1098 case 14: // "mountvers"
1101 case 15: // "nfsprog"
1104 case 16: // "nfsvers"
1109 if (!strncmp(opteq+1, "tcp", 3))
1111 else if (!strncmp(opteq+1, "udp", 3))
1114 bb_error_msg("warning: unrecognized proto= option");
1116 case 19: // "namlen"
1117 if (nfs_mount_version >= 2)
1120 bb_error_msg("warning: option namlen is not supported\n");
1122 case 20: // "addr" - ignore
1125 bb_error_msg("unknown nfs mount parameter: %s=%d", opt, val);
1130 static const char options[] ALIGN1 =
1143 if (!strncmp(opt, "no", 2)) {
1147 switch (index_in_strings(options, opt)) {
1183 if (nfs_mount_version >= 3)
1186 bb_error_msg("warning: option nolock is not supported");
1189 bb_error_msg("unknown nfs mount option: %s%s", val ? "" : "no", opt);
1194 proto = (tcp) ? IPPROTO_TCP : IPPROTO_UDP;
1196 data.flags = (soft ? NFS_MOUNT_SOFT : 0)
1197 | (intr ? NFS_MOUNT_INTR : 0)
1198 | (posix ? NFS_MOUNT_POSIX : 0)
1199 | (nocto ? NFS_MOUNT_NOCTO : 0)
1200 | (noac ? NFS_MOUNT_NOAC : 0);
1201 if (nfs_mount_version >= 2)
1202 data.flags |= (tcp ? NFS_MOUNT_TCP : 0);
1203 if (nfs_mount_version >= 3)
1204 data.flags |= (nolock ? NFS_MOUNT_NONLM : 0);
1205 if (nfsvers > MAX_NFSPROT || mountvers > MAX_NFSPROT) {
1206 bb_error_msg("NFSv%d not supported", nfsvers);
1209 if (nfsvers && !mountvers)
1210 mountvers = (nfsvers < 3) ? 1 : nfsvers;
1211 if (nfsvers && nfsvers < mountvers) {
1212 mountvers = nfsvers;
1215 /* Adjust options if none specified */
1217 data.timeo = tcp ? 70 : 7;
1219 data.version = nfs_mount_version;
1221 if (vfsflags & MS_REMOUNT)
1225 * If the previous mount operation on the same host was
1226 * backgrounded, and the "bg" for this mount is also set,
1227 * give up immediately, to avoid the initial timeout.
1229 if (bg && we_saw_this_host_before(hostname)) {
1230 daemonized = daemonize();
1231 if (daemonized <= 0) { /* parent or error */
1232 retval = -daemonized;
1237 /* create mount daemon client */
1238 /* See if the nfs host = mount host. */
1240 if (mounthost[0] >= '0' && mounthost[0] <= '9') {
1241 mount_server_addr.sin_family = AF_INET;
1242 mount_server_addr.sin_addr.s_addr = inet_addr(hostname);
1244 hp = gethostbyname(mounthost);
1246 bb_herror_msg("%s", mounthost);
1249 if (hp->h_length > sizeof(struct in_addr)) {
1250 bb_error_msg("got bad hp->h_length?");
1251 hp->h_length = sizeof(struct in_addr);
1253 mount_server_addr.sin_family = AF_INET;
1254 memcpy(&mount_server_addr.sin_addr,
1255 hp->h_addr, hp->h_length);
1261 * The following loop implements the mount retries. When the mount
1262 * times out, and the "bg" option is set, we background ourself
1263 * and continue trying.
1265 * The case where the mount point is not present and the "bg"
1266 * option is set, is treated as a timeout. This is done to
1267 * support nested mounts.
1269 * The "retry" count specified by the user is the number of
1270 * minutes to retry before giving up.
1273 struct timeval total_timeout;
1274 struct timeval retry_timeout;
1280 retry_timeout.tv_sec = 3;
1281 retry_timeout.tv_usec = 0;
1282 total_timeout.tv_sec = 20;
1283 total_timeout.tv_usec = 0;
1284 timeout = time(NULL) + 60 * retry;
1288 /* be careful not to use too many CPU cycles */
1292 get_mountport(&pm_mnt, &mount_server_addr,
1297 nfsvers = (pm_mnt.pm_vers < 2) ? 2 : pm_mnt.pm_vers;
1299 /* contact the mount daemon via TCP */
1300 mount_server_addr.sin_port = htons(pm_mnt.pm_port);
1301 msock = RPC_ANYSOCK;
1303 switch (pm_mnt.pm_prot) {
1305 mclient = clntudp_create(&mount_server_addr,
1312 mount_server_addr.sin_port = htons(pm_mnt.pm_port);
1313 msock = RPC_ANYSOCK;
1315 mclient = clnttcp_create(&mount_server_addr,
1324 if (!daemonized && prevt == 0)
1325 error_msg_rpc(clnt_spcreateerror(" "));
1327 enum clnt_stat clnt_stat;
1328 /* try to mount hostname:pathname */
1329 mclient->cl_auth = authunix_create_default();
1331 /* make pointers in xdr_mountres3 NULL so
1332 * that xdr_array allocates memory for us
1334 memset(&status, 0, sizeof(status));
1336 if (pm_mnt.pm_vers == 3)
1337 clnt_stat = clnt_call(mclient, MOUNTPROC3_MNT,
1338 (xdrproc_t) xdr_dirpath,
1339 (caddr_t) &pathname,
1340 (xdrproc_t) xdr_mountres3,
1344 clnt_stat = clnt_call(mclient, MOUNTPROC_MNT,
1345 (xdrproc_t) xdr_dirpath,
1346 (caddr_t) &pathname,
1347 (xdrproc_t) xdr_fhstatus,
1351 if (clnt_stat == RPC_SUCCESS)
1352 goto prepare_kernel_data; /* we're done */
1353 if (errno != ECONNREFUSED) {
1354 error_msg_rpc(clnt_sperror(mclient, " "));
1355 goto fail; /* don't retry */
1357 /* Connection refused */
1358 if (!daemonized && prevt == 0) /* print just once */
1359 error_msg_rpc(clnt_sperror(mclient, " "));
1360 auth_destroy(mclient->cl_auth);
1361 clnt_destroy(mclient);
1367 /* Timeout. We are going to retry... maybe */
1372 daemonized = daemonize();
1373 if (daemonized <= 0) { /* parent or error */
1374 retval = -daemonized;
1381 /* TODO error message */
1387 prepare_kernel_data:
1390 if (status.nfsv2.fhs_status != 0) {
1391 bb_error_msg("%s:%s failed, reason given by server: %s",
1393 nfs_strerror(status.nfsv2.fhs_status));
1396 memcpy(data.root.data,
1397 (char *) status.nfsv2.fhstatus_u.fhs_fhandle,
1399 data.root.size = NFS_FHSIZE;
1400 memcpy(data.old_root.data,
1401 (char *) status.nfsv2.fhstatus_u.fhs_fhandle,
1404 fhandle3 *my_fhandle;
1405 if (status.nfsv3.fhs_status != 0) {
1406 bb_error_msg("%s:%s failed, reason given by server: %s",
1408 nfs_strerror(status.nfsv3.fhs_status));
1411 my_fhandle = &status.nfsv3.mountres3_u.mountinfo.fhandle;
1412 memset(data.old_root.data, 0, NFS_FHSIZE);
1413 memset(&data.root, 0, sizeof(data.root));
1414 data.root.size = my_fhandle->fhandle3_len;
1415 memcpy(data.root.data,
1416 (char *) my_fhandle->fhandle3_val,
1417 my_fhandle->fhandle3_len);
1419 data.flags |= NFS_MOUNT_VER3;
1422 /* create nfs socket for kernel */
1425 if (nfs_mount_version < 3) {
1426 bb_error_msg("NFS over TCP is not supported");
1429 fsock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1431 fsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1433 bb_perror_msg("nfs socket");
1436 if (bindresvport(fsock, 0) < 0) {
1437 bb_perror_msg("nfs bindresvport");
1441 server_addr.sin_port = PMAPPORT;
1442 port = pmap_getport(&server_addr, nfsprog, nfsvers,
1443 tcp ? IPPROTO_TCP : IPPROTO_UDP);
1447 server_addr.sin_port = htons(port);
1449 /* prepare data structure for kernel */
1452 memcpy((char *) &data.addr, (char *) &server_addr, sizeof(data.addr));
1453 strncpy(data.hostname, hostname, sizeof(data.hostname));
1457 auth_destroy(mclient->cl_auth);
1458 clnt_destroy(mclient);
1463 /* We must wait until mount directory is available */
1464 struct stat statbuf;
1466 while (stat(mp->mnt_dir, &statbuf) == -1) {
1468 daemonized = daemonize();
1469 if (daemonized <= 0) { /* parent or error */
1470 // FIXME: parent doesn't close fsock - ??!
1471 retval = -daemonized;
1475 sleep(delay); /* 1, 2, 4, 8, 16, 30, ... */
1482 do_mount: /* perform actual mount */
1484 mp->mnt_type = (char*)"nfs";
1485 retval = mount_it_now(mp, vfsflags, (char*)&data);
1492 auth_destroy(mclient->cl_auth);
1493 clnt_destroy(mclient);
1507 #else /* !ENABLE_FEATURE_MOUNT_NFS */
1509 /* Never called. Call should be optimized out. */
1510 int nfsmount(struct mntent *mp, int vfsflags, char *filteropts);
1512 #endif /* !ENABLE_FEATURE_MOUNT_NFS */
1514 // Mount one directory. Handles CIFS, NFS, loopback, autobind, and filesystem
1515 // type detection. Returns 0 for success, nonzero for failure.
1516 // NB: mp->xxx fields may be trashed on exit
1517 static int singlemount(struct mntent *mp, int ignore_busy)
1519 int rc = -1, vfsflags;
1520 char *loopFile = 0, *filteropts = 0;
1524 vfsflags = parse_mount_options(mp->mnt_opts, &filteropts);
1526 // Treat fstype "auto" as unspecified.
1528 if (mp->mnt_type && strcmp(mp->mnt_type,"auto") == 0)
1531 // Might this be a virtual filesystem?
1533 if (ENABLE_FEATURE_MOUNT_HELPERS
1534 && (strchr(mp->mnt_fsname, '#'))
1536 char *s, *p, *args[35];
1538 for (s = p = mp->mnt_fsname; *s && n < 35-3; ++s) {
1539 if (s[0] == '#' && s[1] != '#') {
1546 args[n++] = mp->mnt_dir;
1548 rc = wait4pid(xspawn(args));
1552 // Might this be an CIFS filesystem?
1554 if (ENABLE_FEATURE_MOUNT_CIFS
1555 && (!mp->mnt_type || strcmp(mp->mnt_type,"cifs") == 0)
1556 && (mp->mnt_fsname[0]=='/' || mp->mnt_fsname[0]=='\\')
1557 && mp->mnt_fsname[0]==mp->mnt_fsname[1]
1559 len_and_sockaddr *lsa;
1564 // Replace '/' with '\' and verify that unc points to "//server/share".
1566 for (s = mp->mnt_fsname; *s; ++s)
1567 if (*s == '/') *s = '\\';
1571 s = strrchr(mp->mnt_fsname, '\\');
1572 if (s <= mp->mnt_fsname+1) goto report_error;
1574 lsa = host2sockaddr(mp->mnt_fsname+2, 0);
1576 if (!lsa) goto report_error;
1578 // insert ip=... option into string flags.
1580 dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
1581 ip = xasprintf("ip=%s", dotted);
1582 parse_mount_options(ip, &filteropts);
1584 // compose new unc '\\server-ip\share'
1585 // (s => slash after hostname)
1587 mp->mnt_fsname = xasprintf("\\\\%s%s", dotted, s);
1590 vfsflags |= MS_MANDLOCK;
1592 mp->mnt_type = (char*)"cifs";
1593 rc = mount_it_now(mp, vfsflags, filteropts);
1594 if (ENABLE_FEATURE_CLEAN_UP) {
1595 free(mp->mnt_fsname);
1603 // Might this be an NFS filesystem?
1605 if (ENABLE_FEATURE_MOUNT_NFS
1606 && (!mp->mnt_type || !strcmp(mp->mnt_type, "nfs"))
1607 && strchr(mp->mnt_fsname, ':') != NULL
1609 rc = nfsmount(mp, vfsflags, filteropts);
1613 // Look at the file. (Not found isn't a failure for remount, or for
1614 // a synthetic filesystem like proc or sysfs.)
1615 // (We use stat, not lstat, in order to allow
1616 // mount symlink_to_file_or_blkdev dir)
1618 if (!stat(mp->mnt_fsname, &st)
1619 && !(vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE))
1621 // Do we need to allocate a loopback device for it?
1623 if (ENABLE_FEATURE_MOUNT_LOOP && S_ISREG(st.st_mode)) {
1624 loopFile = bb_simplify_path(mp->mnt_fsname);
1625 mp->mnt_fsname = NULL; /* will receive malloced loop dev name */
1626 if (set_loop(&(mp->mnt_fsname), loopFile, 0) < 0) {
1627 if (errno == EPERM || errno == EACCES)
1628 bb_error_msg(bb_msg_perm_denied_are_you_root);
1630 bb_perror_msg("cannot setup loop device");
1634 // Autodetect bind mounts
1636 } else if (S_ISDIR(st.st_mode) && !mp->mnt_type)
1637 vfsflags |= MS_BIND;
1640 /* If we know the fstype (or don't need to), jump straight
1641 * to the actual mount. */
1643 if (mp->mnt_type || (vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE)))
1644 rc = mount_it_now(mp, vfsflags, filteropts);
1646 // Loop through filesystem types until mount succeeds
1649 /* Initialize list of block backed filesystems. This has to be
1650 * done here so that during "mount -a", mounts after /proc shows up
1651 * can autodetect. */
1654 fslist = get_block_backed_filesystems();
1655 if (ENABLE_FEATURE_CLEAN_UP && fslist)
1656 atexit(delete_block_backed_filesystems);
1659 for (fl = fslist; fl; fl = fl->link) {
1660 mp->mnt_type = fl->data;
1661 rc = mount_it_now(mp, vfsflags, filteropts);
1666 // If mount failed, clean up loop file (if any).
1668 if (ENABLE_FEATURE_MOUNT_LOOP && rc && loopFile) {
1669 del_loop(mp->mnt_fsname);
1670 if (ENABLE_FEATURE_CLEAN_UP) {
1672 free(mp->mnt_fsname);
1677 if (ENABLE_FEATURE_CLEAN_UP)
1680 if (errno == EBUSY && ignore_busy)
1683 bb_perror_msg("mounting %s on %s failed", mp->mnt_fsname, mp->mnt_dir);
1687 // Parse options, if necessary parse fstab/mtab, and call singlemount for
1688 // each directory to be mounted.
1690 static const char must_be_root[] ALIGN1 = "you must be root";
1692 int mount_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1693 int mount_main(int argc, char **argv)
1695 enum { OPT_ALL = 0x10 };
1697 char *cmdopts = xstrdup(""), *fstype=0, *storage_path=0;
1699 const char *fstabname;
1703 struct mntent mtpair[2], *mtcur = mtpair;
1704 SKIP_DESKTOP(const int nonroot = 0;)
1705 USE_DESKTOP( int nonroot = (getuid() != 0);)
1707 sanitize_env_if_suid();
1709 // Parse long options, like --bind and --move. Note that -o option
1710 // and --option are synonymous. Yes, this means --remount,rw works.
1712 for (i = j = 0; i < argc; i++) {
1713 if (argv[i][0] == '-' && argv[i][1] == '-') {
1714 append_mount_options(&cmdopts, argv[i]+2);
1715 } else argv[j++] = argv[i];
1720 // Parse remaining options
1722 #if ENABLE_FEATURE_MOUNT_VERBOSE
1723 opt_complementary = "vv"; // -v is a counter
1725 opt = getopt32(argv, OPTION_STR, &opt_o, &fstype
1726 USE_FEATURE_MOUNT_VERBOSE(, &verbose));
1727 if (opt & OPT_o) append_mount_options(&cmdopts, opt_o); // -o
1728 if (opt & OPT_r) append_mount_options(&cmdopts, "ro"); // -r
1729 if (opt & OPT_w) append_mount_options(&cmdopts, "rw"); // -w
1733 // Three or more non-option arguments? Die with a usage message.
1735 if (argc > 2) bb_show_usage();
1737 // If we have no arguments, show currently mounted filesystems
1740 if (!(opt & OPT_ALL)) {
1741 FILE *mountTable = setmntent(bb_path_mtab_file, "r");
1743 if (!mountTable) bb_error_msg_and_die("no %s", bb_path_mtab_file);
1745 while (getmntent_r(mountTable, &mtpair[0], getmntent_buf,
1746 sizeof(getmntent_buf)))
1748 // Don't show rootfs. FIXME: why??
1749 // util-linux 2.12a happily shows rootfs...
1750 //if (!strcmp(mtpair->mnt_fsname, "rootfs")) continue;
1752 if (!fstype || !strcmp(mtpair->mnt_type, fstype))
1753 printf("%s on %s type %s (%s)\n", mtpair->mnt_fsname,
1754 mtpair->mnt_dir, mtpair->mnt_type,
1757 if (ENABLE_FEATURE_CLEAN_UP) endmntent(mountTable);
1758 return EXIT_SUCCESS;
1760 } else storage_path = bb_simplify_path(argv[0]);
1762 // When we have two arguments, the second is the directory and we can
1763 // skip looking at fstab entirely. We can always abspath() the directory
1764 // argument when we get it.
1768 bb_error_msg_and_die(must_be_root);
1769 mtpair->mnt_fsname = argv[0];
1770 mtpair->mnt_dir = argv[1];
1771 mtpair->mnt_type = fstype;
1772 mtpair->mnt_opts = cmdopts;
1773 rc = singlemount(mtpair, 0);
1777 i = parse_mount_options(cmdopts, 0);
1778 if (nonroot && (i & ~MS_SILENT)) // Non-root users cannot specify flags
1779 bb_error_msg_and_die(must_be_root);
1781 // If we have a shared subtree flag, don't worry about fstab or mtab.
1783 if (ENABLE_FEATURE_MOUNT_FLAGS
1784 && (i & (MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE))
1786 rc = verbose_mount("", argv[0], "", i, "");
1787 if (rc) bb_simple_perror_msg_and_die(argv[0]);
1791 // Open either fstab or mtab
1793 fstabname = "/etc/fstab";
1794 if (i & MS_REMOUNT) {
1795 fstabname = bb_path_mtab_file;
1797 fstab = setmntent(fstabname, "r");
1799 bb_perror_msg_and_die("cannot read %s", fstabname);
1801 // Loop through entries until we find what we're looking for.
1803 memset(mtpair, 0, sizeof(mtpair));
1805 struct mntent *mtnext = (mtcur==mtpair ? mtpair+1 : mtpair);
1807 // Get next fstab entry
1809 if (!getmntent_r(fstab, mtcur, getmntent_buf
1810 + (mtcur==mtpair ? sizeof(getmntent_buf)/2 : 0),
1811 sizeof(getmntent_buf)/2))
1813 // Were we looking for something specific?
1817 // If we didn't find anything, complain.
1819 if (!mtnext->mnt_fsname)
1820 bb_error_msg_and_die("can't find %s in %s",
1821 argv[0], fstabname);
1825 // fstab must have "users" or "user"
1826 if (!(parse_mount_options(mtcur->mnt_opts, 0) & MOUNT_USERS))
1827 bb_error_msg_and_die(must_be_root);
1830 // Mount the last thing we found.
1832 mtcur->mnt_opts = xstrdup(mtcur->mnt_opts);
1833 append_mount_options(&(mtcur->mnt_opts), cmdopts);
1834 rc = singlemount(mtcur, 0);
1835 free(mtcur->mnt_opts);
1840 /* If we're trying to mount something specific and this isn't it,
1841 * skip it. Note we must match both the exact text in fstab (ala
1842 * "proc") or a full path from root */
1846 // Is this what we're looking for?
1848 if (strcmp(argv[0], mtcur->mnt_fsname) &&
1849 strcmp(storage_path, mtcur->mnt_fsname) &&
1850 strcmp(argv[0], mtcur->mnt_dir) &&
1851 strcmp(storage_path, mtcur->mnt_dir)) continue;
1853 // Remember this entry. Something later may have overmounted
1854 // it, and we want the _last_ match.
1858 // If we're mounting all.
1861 // Do we need to match a filesystem type?
1862 if (fstype && match_fstype(mtcur, fstype)) continue;
1864 // Skip noauto and swap anyway.
1866 if (parse_mount_options(mtcur->mnt_opts, 0)
1867 & (MOUNT_NOAUTO | MOUNT_SWAP)) continue;
1869 // No, mount -a won't mount anything,
1870 // even user mounts, for mere humans.
1873 bb_error_msg_and_die(must_be_root);
1875 // Mount this thing.
1877 // NFS mounts want this to be xrealloc-able
1878 mtcur->mnt_opts = xstrdup(mtcur->mnt_opts);
1879 if (singlemount(mtcur, 1)) {
1880 /* Count number of failed mounts */
1883 free(mtcur->mnt_opts);
1886 if (ENABLE_FEATURE_CLEAN_UP) endmntent(fstab);
1890 if (ENABLE_FEATURE_CLEAN_UP) {