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.
24 /* Needed for nfs support only... */
26 #include <sys/utsname.h>
30 #include <rpc/pmap_prot.h>
31 #include <rpc/pmap_clnt.h>
34 // Not real flags, but we want to be able to check for this.
36 MOUNT_USERS = (1<<28)*ENABLE_DESKTOP,
37 MOUNT_NOAUTO = (1<<29),
40 // TODO: more "user" flag compatibility.
41 // "user" option (from mount manpage):
42 // Only the user that mounted a filesystem can unmount it again.
43 // If any user should be able to unmount, then use users instead of user
44 // in the fstab line. The owner option is similar to the user option,
45 // with the restriction that the user must be the owner of the special file.
46 // This may be useful e.g. for /dev/fd if a login script makes
47 // the console user owner of this device.
49 /* Standard mount options (from -o options or --options), with corresponding
55 } static mount_options[] = {
56 // MS_FLAGS set a bit. ~MS_FLAGS disable that bit. 0 flags are NOPs.
58 USE_FEATURE_MOUNT_LOOP(
62 USE_FEATURE_MOUNT_FSTAB(
65 {"noauto", MOUNT_NOAUTO},
67 USE_DESKTOP({"user", MOUNT_USERS},)
68 USE_DESKTOP({"users", MOUNT_USERS},)
71 USE_FEATURE_MOUNT_FLAGS(
73 {"nosuid", MS_NOSUID},
78 {"noexec", MS_NOEXEC},
79 {"sync", MS_SYNCHRONOUS},
80 {"async", ~MS_SYNCHRONOUS},
81 {"atime", ~MS_NOATIME},
82 {"noatime", MS_NOATIME},
83 {"diratime", ~MS_NODIRATIME},
84 {"nodiratime", MS_NODIRATIME},
91 {"shared", MS_SHARED},
93 {"private", MS_PRIVATE},
94 {"unbindable", MS_UNBINDABLE},
95 {"rshared", MS_SHARED|MS_RECURSIVE},
96 {"rslave", MS_SLAVE|MS_RECURSIVE},
97 {"rprivate", MS_SLAVE|MS_RECURSIVE},
98 {"runbindable", MS_UNBINDABLE|MS_RECURSIVE},
101 // Always understood.
103 {"ro", MS_RDONLY}, // vfs flag
104 {"rw", ~MS_RDONLY}, // vfs flag
105 {"remount", MS_REMOUNT}, // action flag
108 #define VECTOR_SIZE(v) (sizeof(v) / sizeof((v)[0]))
110 /* Append mount options to string */
111 static void append_mount_options(char **oldopts, char *newopts)
113 if (*oldopts && **oldopts) {
114 /* do not insert options which are already there */
117 int len = strlen(newopts);
118 p = strchr(newopts, ',');
119 if (p) len = p - newopts;
122 if (!strncmp(p, newopts, len)
123 && (p[len]==',' || p[len]==0))
129 p = xasprintf("%s,%.*s", *oldopts, len, newopts);
134 while (newopts[0] == ',') newopts++;
137 if (ENABLE_FEATURE_CLEAN_UP) free(*oldopts);
138 *oldopts = xstrdup(newopts);
142 /* Use the mount_options list to parse options into flags.
143 * Also return list of unrecognized options if unrecognized!=NULL */
144 static int parse_mount_options(char *options, char **unrecognized)
146 int flags = MS_SILENT;
148 // Loop through options
151 char *comma = strchr(options, ',');
153 if (comma) *comma = 0;
155 // Find this option in mount_options
156 for (i = 0; i < VECTOR_SIZE(mount_options); i++) {
157 if (!strcasecmp(mount_options[i].name, options)) {
158 long fl = mount_options[i].flags;
159 if (fl < 0) flags &= fl;
164 // If unrecognized not NULL, append unrecognized mount options */
165 if (unrecognized && i == VECTOR_SIZE(mount_options)) {
166 // Add it to strflags, to pass on to kernel
167 i = *unrecognized ? strlen(*unrecognized) : 0;
168 *unrecognized = xrealloc(*unrecognized, i+strlen(options)+2);
170 // Comma separated if it's not the first one
171 if (i) (*unrecognized)[i++] = ',';
172 strcpy((*unrecognized)+i, options);
175 // Advance to next option, or finish
185 // Return a list of all block device backed filesystems
187 static llist_t *get_block_backed_filesystems(void)
189 static const char *const filesystems[] = {
199 for (i = 0; filesystems[i]; i++) {
200 f = fopen(filesystems[i], "r");
203 while ((buf = xmalloc_getline(f)) != 0) {
204 if (!strncmp(buf, "nodev", 5) && isspace(buf[5]))
206 fs = skip_whitespace(buf);
207 if (*fs=='#' || *fs=='*' || !*fs) continue;
209 llist_add_to_end(&list, xstrdup(fs));
212 if (ENABLE_FEATURE_CLEAN_UP) fclose(f);
220 #if ENABLE_FEATURE_CLEAN_UP
221 static void delete_block_backed_filesystems(void)
223 llist_free(fslist, free);
226 void delete_block_backed_filesystems(void);
229 #if ENABLE_FEATURE_MTAB_SUPPORT
230 static int useMtab = 1;
237 // Perform actual mount of specific filesystem at specific location.
238 // NB: mp->xxx fields may be trashed on exit
239 static int mount_it_now(struct mntent *mp, int vfsflags, char *filteropts)
243 if (fakeIt) goto mtab;
245 // Mount, with fallback to read-only if necessary.
248 rc = mount(mp->mnt_fsname, mp->mnt_dir, mp->mnt_type,
249 vfsflags, filteropts);
250 if (!rc || (vfsflags&MS_RDONLY) || (errno!=EACCES && errno!=EROFS))
252 bb_error_msg("%s is write-protected, mounting read-only",
254 vfsflags |= MS_RDONLY;
257 // Abort entirely if permission denied.
259 if (rc && errno == EPERM)
260 bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
262 /* If the mount was successful, and we're maintaining an old-style
263 * mtab file by hand, add the new entry to it now. */
265 if (ENABLE_FEATURE_MTAB_SUPPORT && useMtab && !rc && !(vfsflags & MS_REMOUNT)) {
267 FILE *mountTable = setmntent(bb_path_mtab_file, "a+");
271 bb_error_msg("no %s",bb_path_mtab_file);
275 // Add vfs string flags
277 for (i=0; mount_options[i].flags != MS_REMOUNT; i++)
278 if (mount_options[i].flags > 0 && (mount_options[i].flags & vfsflags))
279 append_mount_options(&(mp->mnt_opts), mount_options[i].name);
281 // Remove trailing / (if any) from directory we mounted on
283 i = strlen(mp->mnt_dir) - 1;
284 if (i > 0 && mp->mnt_dir[i] == '/') mp->mnt_dir[i] = 0;
286 // Convert to canonical pathnames as needed
288 mp->mnt_dir = bb_simplify_path(mp->mnt_dir);
290 if (!mp->mnt_type || !*mp->mnt_type) { /* bind mount */
291 mp->mnt_fsname = fsname = bb_simplify_path(mp->mnt_fsname);
292 mp->mnt_type = "bind";
294 mp->mnt_freq = mp->mnt_passno = 0;
298 addmntent(mountTable, mp);
299 endmntent(mountTable);
300 if (ENABLE_FEATURE_CLEAN_UP) {
309 #if ENABLE_FEATURE_MOUNT_NFS
313 * Copyright (C) 1993 Rick Sladkey <jrs@world.std.com>
315 * Licensed under GPLv2, see file LICENSE in this tarball for details.
317 * Wed Feb 8 12:51:48 1995, biro@yggdrasil.com (Ross Biro): allow all port
318 * numbers to be specified on the command line.
320 * Fri, 8 Mar 1996 18:01:39, Swen Thuemmler <swen@uni-paderborn.de>:
321 * Omit the call to connect() for Linux version 1.3.11 or later.
323 * Wed Oct 1 23:55:28 1997: Dick Streefland <dick_streefland@tasking.com>
324 * Implemented the "bg", "fg" and "retry" mount options for NFS.
326 * 1999-02-22 Arkadiusz Mi¶kiewicz <misiek@misiek.eu.org>
327 * - added Native Language Support
329 * Modified by Olaf Kirch and Trond Myklebust for new NFS code,
333 /* This is just a warning of a common mistake. Possibly this should be a
334 * uclibc faq entry rather than in busybox... */
335 #if defined(__UCLIBC__) && ! defined(__UCLIBC_HAS_RPC__)
336 #error "You need to build uClibc with UCLIBC_HAS_RPC for NFS support."
339 #define MOUNTPORT 635
340 #define MNTPATHLEN 1024
341 #define MNTNAMLEN 255
345 typedef char fhandle[FHSIZE];
348 unsigned int fhandle3_len;
360 MNT3ERR_NAMETOOLONG = 63,
361 MNT3ERR_NOTSUPP = 10004,
362 MNT3ERR_SERVERFAULT = 10006,
364 typedef enum mountstat3 mountstat3;
367 unsigned int fhs_status;
372 typedef struct fhstatus fhstatus;
374 struct mountres3_ok {
377 unsigned int auth_flavours_len;
378 char *auth_flavours_val;
381 typedef struct mountres3_ok mountres3_ok;
384 mountstat3 fhs_status;
386 mountres3_ok mountinfo;
389 typedef struct mountres3 mountres3;
391 typedef char *dirpath;
395 typedef struct mountbody *mountlist;
399 dirpath ml_directory;
402 typedef struct mountbody mountbody;
404 typedef struct groupnode *groups;
410 typedef struct groupnode groupnode;
412 typedef struct exportnode *exports;
419 typedef struct exportnode exportnode;
432 typedef struct ppathcnf ppathcnf;
434 #define MOUNTPROG 100005
437 #define MOUNTPROC_NULL 0
438 #define MOUNTPROC_MNT 1
439 #define MOUNTPROC_DUMP 2
440 #define MOUNTPROC_UMNT 3
441 #define MOUNTPROC_UMNTALL 4
442 #define MOUNTPROC_EXPORT 5
443 #define MOUNTPROC_EXPORTALL 6
445 #define MOUNTVERS_POSIX 2
447 #define MOUNTPROC_PATHCONF 7
451 #define MOUNTPROC3_NULL 0
452 #define MOUNTPROC3_MNT 1
453 #define MOUNTPROC3_DUMP 2
454 #define MOUNTPROC3_UMNT 3
455 #define MOUNTPROC3_UMNTALL 4
456 #define MOUNTPROC3_EXPORT 5
468 * We want to be able to compile mount on old kernels in such a way
469 * that the binary will work well on more recent kernels.
470 * Thus, if necessary we teach nfsmount.c the structure of new fields
471 * that will come later.
473 * Moreover, the new kernel includes conflict with glibc includes
474 * so it is easiest to ignore the kernel altogether (at compile time).
482 unsigned char data[64];
485 struct nfs_mount_data {
488 struct nfs2_fh old_root; /* 1 */
494 int acregmin; /* 1 */
495 int acregmax; /* 1 */
496 int acdirmin; /* 1 */
497 int acdirmax; /* 1 */
498 struct sockaddr_in addr; /* 1 */
499 char hostname[256]; /* 1 */
501 unsigned int bsize; /* 3 */
502 struct nfs3_fh root; /* 4 */
505 /* bits in the flags field */
507 NFS_MOUNT_SOFT = 0x0001, /* 1 */
508 NFS_MOUNT_INTR = 0x0002, /* 1 */
509 NFS_MOUNT_SECURE = 0x0004, /* 1 */
510 NFS_MOUNT_POSIX = 0x0008, /* 1 */
511 NFS_MOUNT_NOCTO = 0x0010, /* 1 */
512 NFS_MOUNT_NOAC = 0x0020, /* 1 */
513 NFS_MOUNT_TCP = 0x0040, /* 2 */
514 NFS_MOUNT_VER3 = 0x0080, /* 3 */
515 NFS_MOUNT_KERBEROS = 0x0100, /* 3 */
516 NFS_MOUNT_NONLM = 0x0200 /* 3 */
521 * We need to translate between nfs status return values and
522 * the local errno values which may not be the same.
524 * Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>: change errno:
525 * "after #include <errno.h> the symbol errno is reserved for any use,
526 * it cannot even be used as a struct tag or field name".
530 #define EDQUOT ENOSPC
533 // Convert each NFSERR_BLAH into EBLAH
535 static const struct {
539 {0,0}, {1,EPERM}, {2,ENOENT}, {5,EIO}, {6,ENXIO}, {13,EACCES}, {17,EEXIST},
540 {19,ENODEV}, {20,ENOTDIR}, {21,EISDIR}, {22,EINVAL}, {27,EFBIG},
541 {28,ENOSPC}, {30,EROFS}, {63,ENAMETOOLONG}, {66,ENOTEMPTY}, {69,EDQUOT},
542 {70,ESTALE}, {71,EREMOTE}, {-1,EIO}
545 static char *nfs_strerror(int status)
548 static char buf[sizeof("unknown nfs status return value: ") + sizeof(int)*3];
550 for (i = 0; nfs_errtbl[i].stat != -1; i++) {
551 if (nfs_errtbl[i].stat == status)
552 return strerror(nfs_errtbl[i].errnum);
554 sprintf(buf, "unknown nfs status return value: %d", status);
558 static bool_t xdr_fhandle(XDR *xdrs, fhandle objp)
560 if (!xdr_opaque(xdrs, objp, FHSIZE))
565 static bool_t xdr_fhstatus(XDR *xdrs, fhstatus *objp)
567 if (!xdr_u_int(xdrs, &objp->fhs_status))
569 switch (objp->fhs_status) {
571 if (!xdr_fhandle(xdrs, objp->fhstatus_u.fhs_fhandle))
580 static bool_t xdr_dirpath(XDR *xdrs, dirpath *objp)
582 if (!xdr_string(xdrs, objp, MNTPATHLEN))
587 static bool_t xdr_fhandle3(XDR *xdrs, fhandle3 *objp)
589 if (!xdr_bytes(xdrs, (char **)&objp->fhandle3_val, (unsigned int *) &objp->fhandle3_len, FHSIZE3))
594 static bool_t xdr_mountres3_ok(XDR *xdrs, mountres3_ok *objp)
596 if (!xdr_fhandle3(xdrs, &objp->fhandle))
598 if (!xdr_array(xdrs, &(objp->auth_flavours.auth_flavours_val), &(objp->auth_flavours.auth_flavours_len), ~0,
599 sizeof (int), (xdrproc_t) xdr_int))
604 static bool_t xdr_mountstat3(XDR *xdrs, mountstat3 *objp)
606 if (!xdr_enum(xdrs, (enum_t *) objp))
611 static bool_t xdr_mountres3(XDR *xdrs, mountres3 *objp)
613 if (!xdr_mountstat3(xdrs, &objp->fhs_status))
615 switch (objp->fhs_status) {
617 if (!xdr_mountres3_ok(xdrs, &objp->mountres3_u.mountinfo))
626 #define MAX_NFSPROT ((nfs_mount_version >= 4) ? 3 : 2)
629 * nfs_mount_version according to the sources seen at compile time.
631 static int nfs_mount_version;
632 static int kernel_version;
635 * Unfortunately, the kernel prints annoying console messages
636 * in case of an unexpected nfs mount version (instead of
637 * just returning some error). Therefore we'll have to try
638 * and figure out what version the kernel expects.
641 * KERNEL_NFS_MOUNT_VERSION: kernel sources at compile time
642 * NFS_MOUNT_VERSION: these nfsmount sources at compile time
643 * nfs_mount_version: version this source and running kernel can handle
646 find_kernel_nfs_mount_version(void)
651 nfs_mount_version = 4; /* default */
653 kernel_version = get_linux_version_code();
654 if (kernel_version) {
655 if (kernel_version < KERNEL_VERSION(2,1,32))
656 nfs_mount_version = 1;
657 else if (kernel_version < KERNEL_VERSION(2,2,18) ||
658 (kernel_version >= KERNEL_VERSION(2,3,0) &&
659 kernel_version < KERNEL_VERSION(2,3,99)))
660 nfs_mount_version = 3;
661 /* else v4 since 2.3.99pre4 */
666 get_mountport(struct sockaddr_in *server_addr,
668 long unsigned version,
672 struct pmaplist *pmap;
673 static struct pmap p = {0, 0, 0, 0};
675 server_addr->sin_port = PMAPPORT;
676 pmap = pmap_getmaps(server_addr);
678 if (version > MAX_NFSPROT)
679 version = MAX_NFSPROT;
688 if (pmap->pml_map.pm_prog != prog)
690 if (!version && p.pm_vers > pmap->pml_map.pm_vers)
692 if (version > 2 && pmap->pml_map.pm_vers != version)
694 if (version && version <= 2 && pmap->pml_map.pm_vers > 2)
696 if (pmap->pml_map.pm_vers > MAX_NFSPROT ||
697 (proto && p.pm_prot && pmap->pml_map.pm_prot != proto) ||
698 (port && pmap->pml_map.pm_port != port))
700 memcpy(&p, &pmap->pml_map, sizeof(p));
702 pmap = pmap->pml_next;
705 p.pm_vers = MOUNTVERS;
707 p.pm_port = MOUNTPORT;
709 p.pm_prot = IPPROTO_TCP;
713 static int daemonize(void)
717 if (pid < 0) /* error */
719 if (pid > 0) /* parent */
722 fd = xopen(bb_dev_null, O_RDWR);
726 if (fd > 2) close(fd);
728 openlog(applet_name, LOG_PID, LOG_DAEMON);
729 logmode = LOGMODE_SYSLOG;
734 static inline int we_saw_this_host_before(const char *hostname)
739 /* RPC strerror analogs are terminally idiotic:
740 * *mandatory* prefix and \n at end.
741 * This hopefully helps. Usage:
742 * error_msg_rpc(clnt_*error*(" ")) */
743 static void error_msg_rpc(const char *msg)
746 while (msg[0] == ' ' || msg[0] == ':') msg++;
748 while (len && msg[len-1] == '\n') len--;
749 bb_error_msg("%.*s", len, msg);
752 // NB: mp->xxx fields may be trashed on exit
753 static int nfsmount(struct mntent *mp, int vfsflags, char *filteropts)
759 struct nfs_mount_data data;
762 struct sockaddr_in server_addr;
763 struct sockaddr_in mount_server_addr;
766 struct fhstatus nfsv2;
767 struct mountres3 nfsv3;
789 find_kernel_nfs_mount_version();
797 /* NB: hostname, mounthost, filteropts must be free()d prior to return */
799 filteropts = xstrdup(filteropts); /* going to trash it later... */
801 hostname = xstrdup(mp->mnt_fsname);
802 /* mount_main() guarantees that ':' is there */
803 s = strchr(hostname, ':');
806 /* Ignore all but first hostname in replicated mounts
807 until they can be fully supported. (mack@sgi.com) */
808 s = strchr(hostname, ',');
811 bb_error_msg("warning: multiple hostnames not supported");
814 server_addr.sin_family = AF_INET;
815 if (!inet_aton(hostname, &server_addr.sin_addr)) {
816 hp = gethostbyname(hostname);
818 bb_herror_msg("%s", hostname);
821 if (hp->h_length > sizeof(struct in_addr)) {
822 bb_error_msg("got bad hp->h_length");
823 hp->h_length = sizeof(struct in_addr);
825 memcpy(&server_addr.sin_addr,
826 hp->h_addr, hp->h_length);
829 memcpy(&mount_server_addr, &server_addr, sizeof(mount_server_addr));
831 /* add IP address to mtab options for use when unmounting */
833 if (!mp->mnt_opts) { /* TODO: actually mp->mnt_opts is never NULL */
834 mp->mnt_opts = xasprintf("addr=%s", inet_ntoa(server_addr.sin_addr));
836 char *tmp = xasprintf("%s%saddr=%s", mp->mnt_opts,
837 mp->mnt_opts[0] ? "," : "",
838 inet_ntoa(server_addr.sin_addr));
843 /* Set default options.
844 * rsize/wsize (and bsize, for ver >= 3) are left 0 in order to
845 * let the kernel decide.
846 * timeo is filled in after we know whether it'll be TCP or UDP. */
847 memset(&data, 0, sizeof(data));
853 data.namlen = NAME_MAX;
862 retry = 10000; /* 10000 minutes ~ 1 week */
865 mountprog = MOUNTPROG;
874 for (opt = strtok(filteropts, ","); opt; opt = strtok(NULL, ",")) {
875 char *opteq = strchr(opt, '=');
877 const char *const options[] = {
889 /* 11 */ "mountport",
890 /* 12 */ "mounthost",
891 /* 13 */ "mountprog",
892 /* 14 */ "mountvers",
901 int val = xatoi_u(opteq + 1);
903 switch (index_in_str_array(options, opt)) {
916 case 4: // "acregmin"
919 case 5: // "acregmax"
922 case 6: // "acdirmin"
925 case 7: // "acdirmax"
940 case 11: // "mountport"
943 case 12: // "mounthost"
944 mounthost = xstrndup(opteq+1,
945 strcspn(opteq+1," \t\n\r,"));
947 case 13: // "mountprog"
950 case 14: // "mountvers"
953 case 15: // "nfsprog"
956 case 16: // "nfsvers"
961 if (!strncmp(opteq+1, "tcp", 3))
963 else if (!strncmp(opteq+1, "udp", 3))
966 bb_error_msg("warning: unrecognized proto= option");
969 if (nfs_mount_version >= 2)
972 bb_error_msg("warning: option namlen is not supported\n");
974 case 20: // "addr" - ignore
977 bb_error_msg("unknown nfs mount parameter: %s=%d", opt, val);
982 const char *const options[] = {
997 if (!strncmp(opt, "no", 2)) {
1001 switch (index_in_str_array(options, opt)) {
1033 if (nfs_mount_version >= 3)
1036 bb_error_msg("warning: option nolock is not supported");
1039 bb_error_msg("unknown nfs mount option: %s%s", val ? "" : "no", opt);
1044 proto = (tcp) ? IPPROTO_TCP : IPPROTO_UDP;
1046 data.flags = (soft ? NFS_MOUNT_SOFT : 0)
1047 | (intr ? NFS_MOUNT_INTR : 0)
1048 | (posix ? NFS_MOUNT_POSIX : 0)
1049 | (nocto ? NFS_MOUNT_NOCTO : 0)
1050 | (noac ? NFS_MOUNT_NOAC : 0);
1051 if (nfs_mount_version >= 2)
1052 data.flags |= (tcp ? NFS_MOUNT_TCP : 0);
1053 if (nfs_mount_version >= 3)
1054 data.flags |= (nolock ? NFS_MOUNT_NONLM : 0);
1055 if (nfsvers > MAX_NFSPROT || mountvers > MAX_NFSPROT) {
1056 bb_error_msg("NFSv%d not supported", nfsvers);
1059 if (nfsvers && !mountvers)
1060 mountvers = (nfsvers < 3) ? 1 : nfsvers;
1061 if (nfsvers && nfsvers < mountvers) {
1062 mountvers = nfsvers;
1065 /* Adjust options if none specified */
1067 data.timeo = tcp ? 70 : 7;
1069 data.version = nfs_mount_version;
1071 if (vfsflags & MS_REMOUNT)
1075 * If the previous mount operation on the same host was
1076 * backgrounded, and the "bg" for this mount is also set,
1077 * give up immediately, to avoid the initial timeout.
1079 if (bg && we_saw_this_host_before(hostname)) {
1080 daemonized = daemonize(); /* parent or error */
1081 if (daemonized <= 0) { /* parent or error */
1082 retval = -daemonized;
1087 /* create mount daemon client */
1088 /* See if the nfs host = mount host. */
1090 if (mounthost[0] >= '0' && mounthost[0] <= '9') {
1091 mount_server_addr.sin_family = AF_INET;
1092 mount_server_addr.sin_addr.s_addr = inet_addr(hostname);
1094 hp = gethostbyname(mounthost);
1096 bb_herror_msg("%s", mounthost);
1099 if (hp->h_length > sizeof(struct in_addr)) {
1100 bb_error_msg("got bad hp->h_length?");
1101 hp->h_length = sizeof(struct in_addr);
1103 mount_server_addr.sin_family = AF_INET;
1104 memcpy(&mount_server_addr.sin_addr,
1105 hp->h_addr, hp->h_length);
1111 * The following loop implements the mount retries. When the mount
1112 * times out, and the "bg" option is set, we background ourself
1113 * and continue trying.
1115 * The case where the mount point is not present and the "bg"
1116 * option is set, is treated as a timeout. This is done to
1117 * support nested mounts.
1119 * The "retry" count specified by the user is the number of
1120 * minutes to retry before giving up.
1123 struct timeval total_timeout;
1124 struct timeval retry_timeout;
1125 struct pmap* pm_mnt;
1130 retry_timeout.tv_sec = 3;
1131 retry_timeout.tv_usec = 0;
1132 total_timeout.tv_sec = 20;
1133 total_timeout.tv_usec = 0;
1134 timeout = time(NULL) + 60 * retry;
1138 /* be careful not to use too many CPU cycles */
1142 pm_mnt = get_mountport(&mount_server_addr,
1147 nfsvers = (pm_mnt->pm_vers < 2) ? 2 : pm_mnt->pm_vers;
1149 /* contact the mount daemon via TCP */
1150 mount_server_addr.sin_port = htons(pm_mnt->pm_port);
1151 msock = RPC_ANYSOCK;
1153 switch (pm_mnt->pm_prot) {
1155 mclient = clntudp_create(&mount_server_addr,
1162 mount_server_addr.sin_port = htons(pm_mnt->pm_port);
1163 msock = RPC_ANYSOCK;
1165 mclient = clnttcp_create(&mount_server_addr,
1174 if (!daemonized && prevt == 0)
1175 error_msg_rpc(clnt_spcreateerror(" "));
1177 enum clnt_stat clnt_stat;
1178 /* try to mount hostname:pathname */
1179 mclient->cl_auth = authunix_create_default();
1181 /* make pointers in xdr_mountres3 NULL so
1182 * that xdr_array allocates memory for us
1184 memset(&status, 0, sizeof(status));
1186 if (pm_mnt->pm_vers == 3)
1187 clnt_stat = clnt_call(mclient, MOUNTPROC3_MNT,
1188 (xdrproc_t) xdr_dirpath,
1189 (caddr_t) &pathname,
1190 (xdrproc_t) xdr_mountres3,
1194 clnt_stat = clnt_call(mclient, MOUNTPROC_MNT,
1195 (xdrproc_t) xdr_dirpath,
1196 (caddr_t) &pathname,
1197 (xdrproc_t) xdr_fhstatus,
1201 if (clnt_stat == RPC_SUCCESS)
1202 goto prepare_kernel_data; /* we're done */
1203 if (errno != ECONNREFUSED) {
1204 error_msg_rpc(clnt_sperror(mclient, " "));
1205 goto fail; /* don't retry */
1207 /* Connection refused */
1208 if (!daemonized && prevt == 0) /* print just once */
1209 error_msg_rpc(clnt_sperror(mclient, " "));
1210 auth_destroy(mclient->cl_auth);
1211 clnt_destroy(mclient);
1216 /* Timeout. We are going to retry... maybe */
1221 daemonized = daemonize();
1222 if (daemonized <= 0) { /* parent or error */
1223 retval = -daemonized;
1230 /* TODO error message */
1236 prepare_kernel_data:
1239 if (status.nfsv2.fhs_status != 0) {
1240 bb_error_msg("%s:%s failed, reason given by server: %s",
1242 nfs_strerror(status.nfsv2.fhs_status));
1245 memcpy(data.root.data,
1246 (char *) status.nfsv2.fhstatus_u.fhs_fhandle,
1248 data.root.size = NFS_FHSIZE;
1249 memcpy(data.old_root.data,
1250 (char *) status.nfsv2.fhstatus_u.fhs_fhandle,
1253 fhandle3 *my_fhandle;
1254 if (status.nfsv3.fhs_status != 0) {
1255 bb_error_msg("%s:%s failed, reason given by server: %s",
1257 nfs_strerror(status.nfsv3.fhs_status));
1260 my_fhandle = &status.nfsv3.mountres3_u.mountinfo.fhandle;
1261 memset(data.old_root.data, 0, NFS_FHSIZE);
1262 memset(&data.root, 0, sizeof(data.root));
1263 data.root.size = my_fhandle->fhandle3_len;
1264 memcpy(data.root.data,
1265 (char *) my_fhandle->fhandle3_val,
1266 my_fhandle->fhandle3_len);
1268 data.flags |= NFS_MOUNT_VER3;
1271 /* create nfs socket for kernel */
1274 if (nfs_mount_version < 3) {
1275 bb_error_msg("NFS over TCP is not supported");
1278 fsock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1280 fsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1282 bb_perror_msg("nfs socket");
1285 if (bindresvport(fsock, 0) < 0) {
1286 bb_perror_msg("nfs bindresvport");
1290 server_addr.sin_port = PMAPPORT;
1291 port = pmap_getport(&server_addr, nfsprog, nfsvers,
1292 tcp ? IPPROTO_TCP : IPPROTO_UDP);
1296 server_addr.sin_port = htons(port);
1298 /* prepare data structure for kernel */
1301 memcpy((char *) &data.addr, (char *) &server_addr, sizeof(data.addr));
1302 strncpy(data.hostname, hostname, sizeof(data.hostname));
1306 auth_destroy(mclient->cl_auth);
1307 clnt_destroy(mclient);
1311 /* We must wait until mount directory is available */
1312 struct stat statbuf;
1314 while (stat(mp->mnt_dir, &statbuf) == -1) {
1316 daemonized = daemonize();
1317 if (daemonized <= 0) { /* parent or error */
1318 retval = -daemonized;
1322 sleep(delay); /* 1, 2, 4, 8, 16, 30, ... */
1329 do_mount: /* perform actual mount */
1331 mp->mnt_type = "nfs";
1332 retval = mount_it_now(mp, vfsflags, (char*)&data);
1339 auth_destroy(mclient->cl_auth);
1340 clnt_destroy(mclient);
1354 #else /* !ENABLE_FEATURE_MOUNT_NFS */
1356 /* Never called. Call should be optimized out. */
1357 int nfsmount(struct mntent *mp, int vfsflags, char *filteropts);
1359 #endif /* !ENABLE_FEATURE_MOUNT_NFS */
1361 // Mount one directory. Handles CIFS, NFS, loopback, autobind, and filesystem
1362 // type detection. Returns 0 for success, nonzero for failure.
1363 // NB: mp->xxx fields may be trashed on exit
1364 static int singlemount(struct mntent *mp, int ignore_busy)
1366 int rc = -1, vfsflags;
1367 char *loopFile = 0, *filteropts = 0;
1371 vfsflags = parse_mount_options(mp->mnt_opts, &filteropts);
1373 // Treat fstype "auto" as unspecified.
1375 if (mp->mnt_type && !strcmp(mp->mnt_type,"auto")) mp->mnt_type = 0;
1377 // Might this be an CIFS filesystem?
1379 if (ENABLE_FEATURE_MOUNT_CIFS &&
1380 (!mp->mnt_type || !strcmp(mp->mnt_type,"cifs")) &&
1381 (mp->mnt_fsname[0]==mp->mnt_fsname[1] && (mp->mnt_fsname[0]=='/' || mp->mnt_fsname[0]=='\\')))
1387 // Replace '/' with '\' and verify that unc points to "//server/share".
1389 for (s = mp->mnt_fsname; *s; ++s)
1390 if (*s == '/') *s = '\\';
1394 s = strrchr(mp->mnt_fsname, '\\');
1395 if (s == mp->mnt_fsname+1) goto report_error;
1397 he = gethostbyname(mp->mnt_fsname+2);
1399 if (!he) goto report_error;
1401 // Insert ip=... option into string flags. (NOTE: Add IPv6 support.)
1403 sprintf(ip, "ip=%d.%d.%d.%d", he->h_addr[0], he->h_addr[1],
1404 he->h_addr[2], he->h_addr[3]);
1405 parse_mount_options(ip, &filteropts);
1407 // compose new unc '\\server-ip\share'
1409 mp->mnt_fsname = xasprintf("\\\\%s%s", ip+3,
1410 strchr(mp->mnt_fsname+2,'\\'));
1413 vfsflags |= MS_MANDLOCK;
1415 mp->mnt_type = "cifs";
1416 rc = mount_it_now(mp, vfsflags, filteropts);
1417 if (ENABLE_FEATURE_CLEAN_UP) free(mp->mnt_fsname);
1421 // Might this be an NFS filesystem?
1423 if (ENABLE_FEATURE_MOUNT_NFS &&
1424 (!mp->mnt_type || !strcmp(mp->mnt_type,"nfs")) &&
1425 strchr(mp->mnt_fsname, ':') != NULL)
1427 rc = nfsmount(mp, vfsflags, filteropts);
1431 // Look at the file. (Not found isn't a failure for remount, or for
1432 // a synthetic filesystem like proc or sysfs.)
1434 if (!lstat(mp->mnt_fsname, &st) && !(vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE)))
1436 // Do we need to allocate a loopback device for it?
1438 if (ENABLE_FEATURE_MOUNT_LOOP && S_ISREG(st.st_mode)) {
1439 loopFile = bb_simplify_path(mp->mnt_fsname);
1441 switch (set_loop(&(mp->mnt_fsname), loopFile, 0)) {
1446 bb_error_msg( errno == EPERM || errno == EACCES
1447 ? bb_msg_perm_denied_are_you_root
1448 : "cannot setup loop device");
1452 // Autodetect bind mounts
1454 } else if (S_ISDIR(st.st_mode) && !mp->mnt_type)
1455 vfsflags |= MS_BIND;
1458 /* If we know the fstype (or don't need to), jump straight
1459 * to the actual mount. */
1461 if (mp->mnt_type || (vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE)))
1462 rc = mount_it_now(mp, vfsflags, filteropts);
1464 // Loop through filesystem types until mount succeeds or we run out
1468 /* Initialize list of block backed filesystems. This has to be
1469 * done here so that during "mount -a", mounts after /proc shows up
1470 * can autodetect. */
1473 fslist = get_block_backed_filesystems();
1474 if (ENABLE_FEATURE_CLEAN_UP && fslist)
1475 atexit(delete_block_backed_filesystems);
1478 for (fl = fslist; fl; fl = fl->link) {
1479 mp->mnt_type = fl->data;
1480 rc = mount_it_now(mp, vfsflags, filteropts);
1485 // If mount failed, clean up loop file (if any).
1487 if (ENABLE_FEATURE_MOUNT_LOOP && rc && loopFile) {
1488 del_loop(mp->mnt_fsname);
1489 if (ENABLE_FEATURE_CLEAN_UP) {
1491 free(mp->mnt_fsname);
1496 if (ENABLE_FEATURE_CLEAN_UP) free(filteropts);
1498 if (rc && errno == EBUSY && ignore_busy) rc = 0;
1500 /* perror here sometimes says "mounting ... on ... failed: Success" */
1501 bb_error_msg("mounting %s on %s failed", mp->mnt_fsname, mp->mnt_dir);
1506 // Parse options, if necessary parse fstab/mtab, and call singlemount for
1507 // each directory to be mounted.
1509 const char must_be_root[] = "you must be root";
1511 int mount_main(int argc, char **argv)
1513 enum { OPT_ALL = 0x10 };
1515 char *cmdopts = xstrdup(""), *fstype=0, *storage_path=0;
1517 const char *fstabname;
1521 struct mntent mtpair[2], *mtcur = mtpair;
1522 SKIP_DESKTOP(const int nonroot = 0;)
1523 USE_DESKTOP( int nonroot = (getuid() != 0);)
1525 /* parse long options, like --bind and --move. Note that -o option
1526 * and --option are synonymous. Yes, this means --remount,rw works. */
1528 for (i = j = 0; i < argc; i++) {
1529 if (argv[i][0] == '-' && argv[i][1] == '-') {
1530 append_mount_options(&cmdopts, argv[i]+2);
1531 } else argv[j++] = argv[i];
1536 // Parse remaining options
1538 opt = getopt32(argc, argv, "o:t:rwanfvs", &opt_o, &fstype);
1539 if (opt & 0x1) append_mount_options(&cmdopts, opt_o); // -o
1540 //if (opt & 0x2) // -t
1541 if (opt & 0x4) append_mount_options(&cmdopts, "ro"); // -r
1542 if (opt & 0x8) append_mount_options(&cmdopts, "rw"); // -w
1543 //if (opt & 0x10) // -a
1544 if (opt & 0x20) USE_FEATURE_MTAB_SUPPORT(useMtab = 0); // -n
1545 if (opt & 0x40) USE_FEATURE_MTAB_SUPPORT(fakeIt = 1); // -f
1546 //if (opt & 0x80) // -v: verbose (ignore)
1547 //if (opt & 0x100) // -s: sloppy (ignore)
1551 // Three or more non-option arguments? Die with a usage message.
1553 if (argc > 2) bb_show_usage();
1555 // If we have no arguments, show currently mounted filesystems
1558 if (!(opt & OPT_ALL)) {
1559 FILE *mountTable = setmntent(bb_path_mtab_file, "r");
1561 if (!mountTable) bb_error_msg_and_die("no %s", bb_path_mtab_file);
1563 while (getmntent_r(mountTable, mtpair, bb_common_bufsiz1,
1564 sizeof(bb_common_bufsiz1)))
1566 // Don't show rootfs. FIXME: why??
1567 if (!strcmp(mtpair->mnt_fsname, "rootfs")) continue;
1569 if (!fstype || !strcmp(mtpair->mnt_type, fstype))
1570 printf("%s on %s type %s (%s)\n", mtpair->mnt_fsname,
1571 mtpair->mnt_dir, mtpair->mnt_type,
1574 if (ENABLE_FEATURE_CLEAN_UP) endmntent(mountTable);
1575 return EXIT_SUCCESS;
1577 } else storage_path = bb_simplify_path(argv[0]);
1579 // When we have two arguments, the second is the directory and we can
1580 // skip looking at fstab entirely. We can always abspath() the directory
1581 // argument when we get it.
1585 bb_error_msg_and_die(must_be_root);
1586 mtpair->mnt_fsname = argv[0];
1587 mtpair->mnt_dir = argv[1];
1588 mtpair->mnt_type = fstype;
1589 mtpair->mnt_opts = cmdopts;
1590 rc = singlemount(mtpair, 0);
1594 i = parse_mount_options(cmdopts, 0);
1595 if (nonroot && (i & ~MS_SILENT)) // Non-root users cannot specify flags
1596 bb_error_msg_and_die(must_be_root);
1598 // If we have a shared subtree flag, don't worry about fstab or mtab.
1600 if (ENABLE_FEATURE_MOUNT_FLAGS &&
1601 (i & (MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE)))
1603 rc = mount("", argv[0], "", i, "");
1604 if (rc) bb_perror_msg_and_die("%s", argv[0]);
1608 // Open either fstab or mtab
1610 fstabname = "/etc/fstab";
1611 if (i & MS_REMOUNT) {
1612 fstabname = bb_path_mtab_file;
1614 fstab = setmntent(fstabname, "r");
1616 bb_perror_msg_and_die("cannot read %s", fstabname);
1618 // Loop through entries until we find what we're looking for.
1620 memset(mtpair, 0, sizeof(mtpair));
1622 struct mntent *mtnext = (mtcur==mtpair ? mtpair+1 : mtpair);
1624 // Get next fstab entry
1626 if (!getmntent_r(fstab, mtcur, bb_common_bufsiz1
1627 + (mtcur==mtpair ? sizeof(bb_common_bufsiz1)/2 : 0),
1628 sizeof(bb_common_bufsiz1)/2))
1630 // Were we looking for something specific?
1634 // If we didn't find anything, complain.
1636 if (!mtnext->mnt_fsname)
1637 bb_error_msg_and_die("can't find %s in %s",
1638 argv[0], fstabname);
1642 // fstab must have "users" or "user"
1643 if (!(parse_mount_options(mtcur->mnt_opts, 0) & MOUNT_USERS))
1644 bb_error_msg_and_die(must_be_root);
1647 // Mount the last thing we found.
1649 mtcur->mnt_opts = xstrdup(mtcur->mnt_opts);
1650 append_mount_options(&(mtcur->mnt_opts), cmdopts);
1651 rc = singlemount(mtcur, 0);
1652 free(mtcur->mnt_opts);
1657 /* If we're trying to mount something specific and this isn't it,
1658 * skip it. Note we must match both the exact text in fstab (ala
1659 * "proc") or a full path from root */
1663 // Is this what we're looking for?
1665 if (strcmp(argv[0], mtcur->mnt_fsname) &&
1666 strcmp(storage_path, mtcur->mnt_fsname) &&
1667 strcmp(argv[0], mtcur->mnt_dir) &&
1668 strcmp(storage_path, mtcur->mnt_dir)) continue;
1670 // Remember this entry. Something later may have overmounted
1671 // it, and we want the _last_ match.
1675 // If we're mounting all.
1678 // Do we need to match a filesystem type?
1679 // TODO: support "-t type1,type2"; "-t notype1,type2"
1681 if (fstype && strcmp(mtcur->mnt_type, fstype)) continue;
1683 // Skip noauto and swap anyway.
1685 if (parse_mount_options(mtcur->mnt_opts, 0)
1686 & (MOUNT_NOAUTO | MOUNT_SWAP)) continue;
1688 // No, mount -a won't mount anything,
1689 // even user mounts, for mere humans.
1692 bb_error_msg_and_die(must_be_root);
1694 // Mount this thing.
1696 if (singlemount(mtcur, 1)) {
1697 /* Count number of failed mounts */
1702 if (ENABLE_FEATURE_CLEAN_UP) endmntent(fstab);
1706 if (ENABLE_FEATURE_CLEAN_UP) {