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 #if defined(__dietlibc__)
35 /* 16.12.2006, Sampo Kellomaki (sampo@iki.fi)
36 * dietlibc-0.30 does not have implementation of getmntent_r() */
37 /* OTOH: why we use getmntent_r instead of getmntent? TODO... */
38 struct mntent *getmntent_r(FILE* stream, struct mntent* result, char* buffer, int bufsize)
40 /* *** XXX FIXME WARNING: This hack is NOT thread safe. --Sampo */
41 struct mntent* ment = getmntent(stream);
42 memcpy(result, ment, sizeof(struct mntent));
48 // Not real flags, but we want to be able to check for this.
50 MOUNT_USERS = (1<<28)*ENABLE_DESKTOP,
51 MOUNT_NOAUTO = (1<<29),
54 // TODO: more "user" flag compatibility.
55 // "user" option (from mount manpage):
56 // Only the user that mounted a filesystem can unmount it again.
57 // If any user should be able to unmount, then use users instead of user
58 // in the fstab line. The owner option is similar to the user option,
59 // with the restriction that the user must be the owner of the special file.
60 // This may be useful e.g. for /dev/fd if a login script makes
61 // the console user owner of this device.
63 /* Standard mount options (from -o options or --options), with corresponding
69 } static mount_options[] = {
70 // MS_FLAGS set a bit. ~MS_FLAGS disable that bit. 0 flags are NOPs.
72 USE_FEATURE_MOUNT_LOOP(
76 USE_FEATURE_MOUNT_FSTAB(
78 /* {"quiet", 0}, - do not filter out, vfat wants to see it */
79 {"noauto", MOUNT_NOAUTO},
82 USE_DESKTOP({"user", MOUNT_USERS},)
83 USE_DESKTOP({"users", MOUNT_USERS},)
86 USE_FEATURE_MOUNT_FLAGS(
88 {"nosuid", MS_NOSUID},
93 {"noexec", MS_NOEXEC},
94 {"sync", MS_SYNCHRONOUS},
95 {"async", ~MS_SYNCHRONOUS},
96 {"atime", ~MS_NOATIME},
97 {"noatime", MS_NOATIME},
98 {"diratime", ~MS_NODIRATIME},
99 {"nodiratime", MS_NODIRATIME},
100 {"loud", ~MS_SILENT},
106 {"shared", MS_SHARED},
108 {"private", MS_PRIVATE},
109 {"unbindable", MS_UNBINDABLE},
110 {"rshared", MS_SHARED|MS_RECURSIVE},
111 {"rslave", MS_SLAVE|MS_RECURSIVE},
112 {"rprivate", MS_SLAVE|MS_RECURSIVE},
113 {"runbindable", MS_UNBINDABLE|MS_RECURSIVE},
116 // Always understood.
118 {"ro", MS_RDONLY}, // vfs flag
119 {"rw", ~MS_RDONLY}, // vfs flag
120 {"remount", MS_REMOUNT}, // action flag
124 /* Append mount options to string */
125 static void append_mount_options(char **oldopts, const char *newopts)
127 if (*oldopts && **oldopts) {
128 /* do not insert options which are already there */
131 int len = strlen(newopts);
132 p = strchr(newopts, ',');
133 if (p) len = p - newopts;
136 if (!strncmp(p, newopts, len)
137 && (p[len]==',' || p[len]==0))
143 p = xasprintf("%s,%.*s", *oldopts, len, newopts);
148 while (newopts[0] == ',') newopts++;
151 if (ENABLE_FEATURE_CLEAN_UP) free(*oldopts);
152 *oldopts = xstrdup(newopts);
156 /* Use the mount_options list to parse options into flags.
157 * Also return list of unrecognized options if unrecognized!=NULL */
158 static int parse_mount_options(char *options, char **unrecognized)
160 int flags = MS_SILENT;
162 // Loop through options
165 char *comma = strchr(options, ',');
167 if (comma) *comma = 0;
169 // Find this option in mount_options
170 for (i = 0; i < ARRAY_SIZE(mount_options); i++) {
171 if (!strcasecmp(mount_options[i].name, options)) {
172 long fl = mount_options[i].flags;
173 if (fl < 0) flags &= fl;
178 // If unrecognized not NULL, append unrecognized mount options */
179 if (unrecognized && i == ARRAY_SIZE(mount_options)) {
180 // Add it to strflags, to pass on to kernel
181 i = *unrecognized ? strlen(*unrecognized) : 0;
182 *unrecognized = xrealloc(*unrecognized, i+strlen(options)+2);
184 // Comma separated if it's not the first one
185 if (i) (*unrecognized)[i++] = ',';
186 strcpy((*unrecognized)+i, options);
189 // Advance to next option, or finish
199 // Return a list of all block device backed filesystems
201 static llist_t *get_block_backed_filesystems(void)
203 static const char filesystems[2][sizeof("/proc/filesystems")] = {
212 for (i = 0; i < 2; i++) {
213 f = fopen(filesystems[i], "r");
216 while ((buf = xmalloc_getline(f)) != 0) {
217 if (!strncmp(buf, "nodev", 5) && isspace(buf[5]))
219 fs = skip_whitespace(buf);
220 if (*fs=='#' || *fs=='*' || !*fs) continue;
222 llist_add_to_end(&list, xstrdup(fs));
225 if (ENABLE_FEATURE_CLEAN_UP) fclose(f);
233 #if ENABLE_FEATURE_CLEAN_UP
234 static void delete_block_backed_filesystems(void)
236 llist_free(fslist, free);
239 void delete_block_backed_filesystems(void);
242 #if ENABLE_FEATURE_MTAB_SUPPORT
243 static int useMtab = 1;
250 // Perform actual mount of specific filesystem at specific location.
251 // NB: mp->xxx fields may be trashed on exit
252 static int mount_it_now(struct mntent *mp, int vfsflags, char *filteropts)
256 if (fakeIt) goto mtab;
258 // Mount, with fallback to read-only if necessary.
261 rc = mount(mp->mnt_fsname, mp->mnt_dir, mp->mnt_type,
262 vfsflags, filteropts);
263 if (!rc || (vfsflags&MS_RDONLY) || (errno!=EACCES && errno!=EROFS))
265 bb_error_msg("%s is write-protected, mounting read-only",
267 vfsflags |= MS_RDONLY;
270 // Abort entirely if permission denied.
272 if (rc && errno == EPERM)
273 bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
275 /* If the mount was successful, and we're maintaining an old-style
276 * mtab file by hand, add the new entry to it now. */
278 if (ENABLE_FEATURE_MTAB_SUPPORT && useMtab && !rc && !(vfsflags & MS_REMOUNT)) {
280 FILE *mountTable = setmntent(bb_path_mtab_file, "a+");
284 bb_error_msg("no %s",bb_path_mtab_file);
288 // Add vfs string flags
290 for (i=0; mount_options[i].flags != MS_REMOUNT; i++)
291 if (mount_options[i].flags > 0 && (mount_options[i].flags & vfsflags))
292 append_mount_options(&(mp->mnt_opts), mount_options[i].name);
294 // Remove trailing / (if any) from directory we mounted on
296 i = strlen(mp->mnt_dir) - 1;
297 if (i > 0 && mp->mnt_dir[i] == '/') mp->mnt_dir[i] = 0;
299 // Convert to canonical pathnames as needed
301 mp->mnt_dir = bb_simplify_path(mp->mnt_dir);
303 if (!mp->mnt_type || !*mp->mnt_type) { /* bind mount */
304 mp->mnt_fsname = fsname = bb_simplify_path(mp->mnt_fsname);
305 mp->mnt_type = (char*)"bind";
307 mp->mnt_freq = mp->mnt_passno = 0;
311 addmntent(mountTable, mp);
312 endmntent(mountTable);
313 if (ENABLE_FEATURE_CLEAN_UP) {
322 #if ENABLE_FEATURE_MOUNT_NFS
326 * Copyright (C) 1993 Rick Sladkey <jrs@world.std.com>
328 * Licensed under GPLv2, see file LICENSE in this tarball for details.
330 * Wed Feb 8 12:51:48 1995, biro@yggdrasil.com (Ross Biro): allow all port
331 * numbers to be specified on the command line.
333 * Fri, 8 Mar 1996 18:01:39, Swen Thuemmler <swen@uni-paderborn.de>:
334 * Omit the call to connect() for Linux version 1.3.11 or later.
336 * Wed Oct 1 23:55:28 1997: Dick Streefland <dick_streefland@tasking.com>
337 * Implemented the "bg", "fg" and "retry" mount options for NFS.
339 * 1999-02-22 Arkadiusz Mi¶kiewicz <misiek@misiek.eu.org>
340 * - added Native Language Support
342 * Modified by Olaf Kirch and Trond Myklebust for new NFS code,
346 /* This is just a warning of a common mistake. Possibly this should be a
347 * uclibc faq entry rather than in busybox... */
348 #if defined(__UCLIBC__) && ! defined(__UCLIBC_HAS_RPC__)
349 #error "You need to build uClibc with UCLIBC_HAS_RPC for NFS support."
352 #define MOUNTPORT 635
353 #define MNTPATHLEN 1024
354 #define MNTNAMLEN 255
358 typedef char fhandle[FHSIZE];
361 unsigned int fhandle3_len;
373 MNT3ERR_NAMETOOLONG = 63,
374 MNT3ERR_NOTSUPP = 10004,
375 MNT3ERR_SERVERFAULT = 10006,
377 typedef enum mountstat3 mountstat3;
380 unsigned int fhs_status;
385 typedef struct fhstatus fhstatus;
387 struct mountres3_ok {
390 unsigned int auth_flavours_len;
391 char *auth_flavours_val;
394 typedef struct mountres3_ok mountres3_ok;
397 mountstat3 fhs_status;
399 mountres3_ok mountinfo;
402 typedef struct mountres3 mountres3;
404 typedef char *dirpath;
408 typedef struct mountbody *mountlist;
412 dirpath ml_directory;
415 typedef struct mountbody mountbody;
417 typedef struct groupnode *groups;
423 typedef struct groupnode groupnode;
425 typedef struct exportnode *exports;
432 typedef struct exportnode exportnode;
445 typedef struct ppathcnf ppathcnf;
447 #define MOUNTPROG 100005
450 #define MOUNTPROC_NULL 0
451 #define MOUNTPROC_MNT 1
452 #define MOUNTPROC_DUMP 2
453 #define MOUNTPROC_UMNT 3
454 #define MOUNTPROC_UMNTALL 4
455 #define MOUNTPROC_EXPORT 5
456 #define MOUNTPROC_EXPORTALL 6
458 #define MOUNTVERS_POSIX 2
460 #define MOUNTPROC_PATHCONF 7
464 #define MOUNTPROC3_NULL 0
465 #define MOUNTPROC3_MNT 1
466 #define MOUNTPROC3_DUMP 2
467 #define MOUNTPROC3_UMNT 3
468 #define MOUNTPROC3_UMNTALL 4
469 #define MOUNTPROC3_EXPORT 5
481 * We want to be able to compile mount on old kernels in such a way
482 * that the binary will work well on more recent kernels.
483 * Thus, if necessary we teach nfsmount.c the structure of new fields
484 * that will come later.
486 * Moreover, the new kernel includes conflict with glibc includes
487 * so it is easiest to ignore the kernel altogether (at compile time).
495 unsigned char data[64];
498 struct nfs_mount_data {
501 struct nfs2_fh old_root; /* 1 */
507 int acregmin; /* 1 */
508 int acregmax; /* 1 */
509 int acdirmin; /* 1 */
510 int acdirmax; /* 1 */
511 struct sockaddr_in addr; /* 1 */
512 char hostname[256]; /* 1 */
514 unsigned int bsize; /* 3 */
515 struct nfs3_fh root; /* 4 */
518 /* bits in the flags field */
520 NFS_MOUNT_SOFT = 0x0001, /* 1 */
521 NFS_MOUNT_INTR = 0x0002, /* 1 */
522 NFS_MOUNT_SECURE = 0x0004, /* 1 */
523 NFS_MOUNT_POSIX = 0x0008, /* 1 */
524 NFS_MOUNT_NOCTO = 0x0010, /* 1 */
525 NFS_MOUNT_NOAC = 0x0020, /* 1 */
526 NFS_MOUNT_TCP = 0x0040, /* 2 */
527 NFS_MOUNT_VER3 = 0x0080, /* 3 */
528 NFS_MOUNT_KERBEROS = 0x0100, /* 3 */
529 NFS_MOUNT_NONLM = 0x0200 /* 3 */
534 * We need to translate between nfs status return values and
535 * the local errno values which may not be the same.
537 * Andreas Schwab <schwab@LS5.informatik.uni-dortmund.de>: change errno:
538 * "after #include <errno.h> the symbol errno is reserved for any use,
539 * it cannot even be used as a struct tag or field name".
543 #define EDQUOT ENOSPC
546 // Convert each NFSERR_BLAH into EBLAH
548 static const struct {
552 {0,0}, {1,EPERM}, {2,ENOENT}, {5,EIO}, {6,ENXIO}, {13,EACCES}, {17,EEXIST},
553 {19,ENODEV}, {20,ENOTDIR}, {21,EISDIR}, {22,EINVAL}, {27,EFBIG},
554 {28,ENOSPC}, {30,EROFS}, {63,ENAMETOOLONG}, {66,ENOTEMPTY}, {69,EDQUOT},
555 {70,ESTALE}, {71,EREMOTE}, {-1,EIO}
558 static char *nfs_strerror(int status)
561 static char buf[sizeof("unknown nfs status return value: ") + sizeof(int)*3];
563 for (i = 0; nfs_errtbl[i].stat != -1; i++) {
564 if (nfs_errtbl[i].stat == status)
565 return strerror(nfs_errtbl[i].errnum);
567 sprintf(buf, "unknown nfs status return value: %d", status);
571 static bool_t xdr_fhandle(XDR *xdrs, fhandle objp)
573 if (!xdr_opaque(xdrs, objp, FHSIZE))
578 static bool_t xdr_fhstatus(XDR *xdrs, fhstatus *objp)
580 if (!xdr_u_int(xdrs, &objp->fhs_status))
582 switch (objp->fhs_status) {
584 if (!xdr_fhandle(xdrs, objp->fhstatus_u.fhs_fhandle))
593 static bool_t xdr_dirpath(XDR *xdrs, dirpath *objp)
595 if (!xdr_string(xdrs, objp, MNTPATHLEN))
600 static bool_t xdr_fhandle3(XDR *xdrs, fhandle3 *objp)
602 if (!xdr_bytes(xdrs, (char **)&objp->fhandle3_val, (unsigned int *) &objp->fhandle3_len, FHSIZE3))
607 static bool_t xdr_mountres3_ok(XDR *xdrs, mountres3_ok *objp)
609 if (!xdr_fhandle3(xdrs, &objp->fhandle))
611 if (!xdr_array(xdrs, &(objp->auth_flavours.auth_flavours_val), &(objp->auth_flavours.auth_flavours_len), ~0,
612 sizeof (int), (xdrproc_t) xdr_int))
617 static bool_t xdr_mountstat3(XDR *xdrs, mountstat3 *objp)
619 if (!xdr_enum(xdrs, (enum_t *) objp))
624 static bool_t xdr_mountres3(XDR *xdrs, mountres3 *objp)
626 if (!xdr_mountstat3(xdrs, &objp->fhs_status))
628 switch (objp->fhs_status) {
630 if (!xdr_mountres3_ok(xdrs, &objp->mountres3_u.mountinfo))
639 #define MAX_NFSPROT ((nfs_mount_version >= 4) ? 3 : 2)
642 * nfs_mount_version according to the sources seen at compile time.
644 static int nfs_mount_version;
645 static int kernel_version;
648 * Unfortunately, the kernel prints annoying console messages
649 * in case of an unexpected nfs mount version (instead of
650 * just returning some error). Therefore we'll have to try
651 * and figure out what version the kernel expects.
654 * KERNEL_NFS_MOUNT_VERSION: kernel sources at compile time
655 * NFS_MOUNT_VERSION: these nfsmount sources at compile time
656 * nfs_mount_version: version this source and running kernel can handle
659 find_kernel_nfs_mount_version(void)
664 nfs_mount_version = 4; /* default */
666 kernel_version = get_linux_version_code();
667 if (kernel_version) {
668 if (kernel_version < KERNEL_VERSION(2,1,32))
669 nfs_mount_version = 1;
670 else if (kernel_version < KERNEL_VERSION(2,2,18) ||
671 (kernel_version >= KERNEL_VERSION(2,3,0) &&
672 kernel_version < KERNEL_VERSION(2,3,99)))
673 nfs_mount_version = 3;
674 /* else v4 since 2.3.99pre4 */
679 get_mountport(struct sockaddr_in *server_addr,
681 long unsigned version,
685 struct pmaplist *pmap;
686 static struct pmap p = {0, 0, 0, 0};
688 server_addr->sin_port = PMAPPORT;
689 /* glibc 2.4 (still) has pmap_getmaps(struct sockaddr_in *).
690 * I understand it like "IPv6 for this is not 100% ready" */
691 pmap = pmap_getmaps(server_addr);
693 if (version > MAX_NFSPROT)
694 version = MAX_NFSPROT;
703 if (pmap->pml_map.pm_prog != prog)
705 if (!version && p.pm_vers > pmap->pml_map.pm_vers)
707 if (version > 2 && pmap->pml_map.pm_vers != version)
709 if (version && version <= 2 && pmap->pml_map.pm_vers > 2)
711 if (pmap->pml_map.pm_vers > MAX_NFSPROT ||
712 (proto && p.pm_prot && pmap->pml_map.pm_prot != proto) ||
713 (port && pmap->pml_map.pm_port != port))
715 memcpy(&p, &pmap->pml_map, sizeof(p));
717 pmap = pmap->pml_next;
720 p.pm_vers = MOUNTVERS;
722 p.pm_port = MOUNTPORT;
724 p.pm_prot = IPPROTO_TCP;
729 static int daemonize(void)
733 if (pid < 0) /* error */
735 if (pid > 0) /* parent */
738 fd = xopen(bb_dev_null, O_RDWR);
742 while (fd > 2) close(fd--);
744 openlog(applet_name, LOG_PID, LOG_DAEMON);
745 logmode = LOGMODE_SYSLOG;
749 static inline int daemonize(void) { return -ENOSYS; }
753 static inline int we_saw_this_host_before(const char *hostname)
758 /* RPC strerror analogs are terminally idiotic:
759 * *mandatory* prefix and \n at end.
760 * This hopefully helps. Usage:
761 * error_msg_rpc(clnt_*error*(" ")) */
762 static void error_msg_rpc(const char *msg)
765 while (msg[0] == ' ' || msg[0] == ':') msg++;
767 while (len && msg[len-1] == '\n') len--;
768 bb_error_msg("%.*s", len, msg);
771 // NB: mp->xxx fields may be trashed on exit
772 static int nfsmount(struct mntent *mp, int vfsflags, char *filteropts)
778 struct nfs_mount_data data;
781 struct sockaddr_in server_addr;
782 struct sockaddr_in mount_server_addr;
785 struct fhstatus nfsv2;
786 struct mountres3 nfsv3;
812 find_kernel_nfs_mount_version();
820 /* NB: hostname, mounthost, filteropts must be free()d prior to return */
822 filteropts = xstrdup(filteropts); /* going to trash it later... */
824 hostname = xstrdup(mp->mnt_fsname);
825 /* mount_main() guarantees that ':' is there */
826 s = strchr(hostname, ':');
829 /* Ignore all but first hostname in replicated mounts
830 until they can be fully supported. (mack@sgi.com) */
831 s = strchr(hostname, ',');
834 bb_error_msg("warning: multiple hostnames not supported");
837 server_addr.sin_family = AF_INET;
838 if (!inet_aton(hostname, &server_addr.sin_addr)) {
839 hp = gethostbyname(hostname);
841 bb_herror_msg("%s", hostname);
844 if (hp->h_length > sizeof(struct in_addr)) {
845 bb_error_msg("got bad hp->h_length");
846 hp->h_length = sizeof(struct in_addr);
848 memcpy(&server_addr.sin_addr,
849 hp->h_addr, hp->h_length);
852 memcpy(&mount_server_addr, &server_addr, sizeof(mount_server_addr));
854 /* add IP address to mtab options for use when unmounting */
856 if (!mp->mnt_opts) { /* TODO: actually mp->mnt_opts is never NULL */
857 mp->mnt_opts = xasprintf("addr=%s", inet_ntoa(server_addr.sin_addr));
859 char *tmp = xasprintf("%s%saddr=%s", mp->mnt_opts,
860 mp->mnt_opts[0] ? "," : "",
861 inet_ntoa(server_addr.sin_addr));
866 /* Set default options.
867 * rsize/wsize (and bsize, for ver >= 3) are left 0 in order to
868 * let the kernel decide.
869 * timeo is filled in after we know whether it'll be TCP or UDP. */
870 memset(&data, 0, sizeof(data));
876 data.namlen = NAME_MAX;
884 retry = 10000; /* 10000 minutes ~ 1 week */
887 mountprog = MOUNTPROG;
895 if (filteropts) for (opt = strtok(filteropts, ","); opt; opt = strtok(NULL, ",")) {
896 char *opteq = strchr(opt, '=');
898 static const char options[] ALIGN1 =
910 /* 11 */ "mountport\0"
911 /* 12 */ "mounthost\0"
912 /* 13 */ "mountprog\0"
913 /* 14 */ "mountvers\0"
920 int val = xatoi_u(opteq + 1);
922 switch (index_in_strings(options, opt)) {
935 case 4: // "acregmin"
938 case 5: // "acregmax"
941 case 6: // "acdirmin"
944 case 7: // "acdirmax"
959 case 11: // "mountport"
962 case 12: // "mounthost"
963 mounthost = xstrndup(opteq+1,
964 strcspn(opteq+1," \t\n\r,"));
966 case 13: // "mountprog"
969 case 14: // "mountvers"
972 case 15: // "nfsprog"
975 case 16: // "nfsvers"
980 if (!strncmp(opteq+1, "tcp", 3))
982 else if (!strncmp(opteq+1, "udp", 3))
985 bb_error_msg("warning: unrecognized proto= option");
988 if (nfs_mount_version >= 2)
991 bb_error_msg("warning: option namlen is not supported\n");
993 case 20: // "addr" - ignore
996 bb_error_msg("unknown nfs mount parameter: %s=%d", opt, val);
1001 static const char options[] ALIGN1 =
1014 if (!strncmp(opt, "no", 2)) {
1018 switch (index_in_strings(options, opt)) {
1054 if (nfs_mount_version >= 3)
1057 bb_error_msg("warning: option nolock is not supported");
1060 bb_error_msg("unknown nfs mount option: %s%s", val ? "" : "no", opt);
1065 proto = (tcp) ? IPPROTO_TCP : IPPROTO_UDP;
1067 data.flags = (soft ? NFS_MOUNT_SOFT : 0)
1068 | (intr ? NFS_MOUNT_INTR : 0)
1069 | (posix ? NFS_MOUNT_POSIX : 0)
1070 | (nocto ? NFS_MOUNT_NOCTO : 0)
1071 | (noac ? NFS_MOUNT_NOAC : 0);
1072 if (nfs_mount_version >= 2)
1073 data.flags |= (tcp ? NFS_MOUNT_TCP : 0);
1074 if (nfs_mount_version >= 3)
1075 data.flags |= (nolock ? NFS_MOUNT_NONLM : 0);
1076 if (nfsvers > MAX_NFSPROT || mountvers > MAX_NFSPROT) {
1077 bb_error_msg("NFSv%d not supported", nfsvers);
1080 if (nfsvers && !mountvers)
1081 mountvers = (nfsvers < 3) ? 1 : nfsvers;
1082 if (nfsvers && nfsvers < mountvers) {
1083 mountvers = nfsvers;
1086 /* Adjust options if none specified */
1088 data.timeo = tcp ? 70 : 7;
1090 data.version = nfs_mount_version;
1092 if (vfsflags & MS_REMOUNT)
1096 * If the previous mount operation on the same host was
1097 * backgrounded, and the "bg" for this mount is also set,
1098 * give up immediately, to avoid the initial timeout.
1100 if (bg && we_saw_this_host_before(hostname)) {
1101 daemonized = daemonize();
1102 if (daemonized <= 0) { /* parent or error */
1103 retval = -daemonized;
1108 /* create mount daemon client */
1109 /* See if the nfs host = mount host. */
1111 if (mounthost[0] >= '0' && mounthost[0] <= '9') {
1112 mount_server_addr.sin_family = AF_INET;
1113 mount_server_addr.sin_addr.s_addr = inet_addr(hostname);
1115 hp = gethostbyname(mounthost);
1117 bb_herror_msg("%s", mounthost);
1120 if (hp->h_length > sizeof(struct in_addr)) {
1121 bb_error_msg("got bad hp->h_length?");
1122 hp->h_length = sizeof(struct in_addr);
1124 mount_server_addr.sin_family = AF_INET;
1125 memcpy(&mount_server_addr.sin_addr,
1126 hp->h_addr, hp->h_length);
1132 * The following loop implements the mount retries. When the mount
1133 * times out, and the "bg" option is set, we background ourself
1134 * and continue trying.
1136 * The case where the mount point is not present and the "bg"
1137 * option is set, is treated as a timeout. This is done to
1138 * support nested mounts.
1140 * The "retry" count specified by the user is the number of
1141 * minutes to retry before giving up.
1144 struct timeval total_timeout;
1145 struct timeval retry_timeout;
1146 struct pmap* pm_mnt;
1151 retry_timeout.tv_sec = 3;
1152 retry_timeout.tv_usec = 0;
1153 total_timeout.tv_sec = 20;
1154 total_timeout.tv_usec = 0;
1155 timeout = time(NULL) + 60 * retry;
1159 /* be careful not to use too many CPU cycles */
1163 pm_mnt = get_mountport(&mount_server_addr,
1168 nfsvers = (pm_mnt->pm_vers < 2) ? 2 : pm_mnt->pm_vers;
1170 /* contact the mount daemon via TCP */
1171 mount_server_addr.sin_port = htons(pm_mnt->pm_port);
1172 msock = RPC_ANYSOCK;
1174 switch (pm_mnt->pm_prot) {
1176 mclient = clntudp_create(&mount_server_addr,
1183 mount_server_addr.sin_port = htons(pm_mnt->pm_port);
1184 msock = RPC_ANYSOCK;
1186 mclient = clnttcp_create(&mount_server_addr,
1195 if (!daemonized && prevt == 0)
1196 error_msg_rpc(clnt_spcreateerror(" "));
1198 enum clnt_stat clnt_stat;
1199 /* try to mount hostname:pathname */
1200 mclient->cl_auth = authunix_create_default();
1202 /* make pointers in xdr_mountres3 NULL so
1203 * that xdr_array allocates memory for us
1205 memset(&status, 0, sizeof(status));
1207 if (pm_mnt->pm_vers == 3)
1208 clnt_stat = clnt_call(mclient, MOUNTPROC3_MNT,
1209 (xdrproc_t) xdr_dirpath,
1210 (caddr_t) &pathname,
1211 (xdrproc_t) xdr_mountres3,
1215 clnt_stat = clnt_call(mclient, MOUNTPROC_MNT,
1216 (xdrproc_t) xdr_dirpath,
1217 (caddr_t) &pathname,
1218 (xdrproc_t) xdr_fhstatus,
1222 if (clnt_stat == RPC_SUCCESS)
1223 goto prepare_kernel_data; /* we're done */
1224 if (errno != ECONNREFUSED) {
1225 error_msg_rpc(clnt_sperror(mclient, " "));
1226 goto fail; /* don't retry */
1228 /* Connection refused */
1229 if (!daemonized && prevt == 0) /* print just once */
1230 error_msg_rpc(clnt_sperror(mclient, " "));
1231 auth_destroy(mclient->cl_auth);
1232 clnt_destroy(mclient);
1238 /* Timeout. We are going to retry... maybe */
1243 daemonized = daemonize();
1244 if (daemonized <= 0) { /* parent or error */
1245 retval = -daemonized;
1252 /* TODO error message */
1258 prepare_kernel_data:
1261 if (status.nfsv2.fhs_status != 0) {
1262 bb_error_msg("%s:%s failed, reason given by server: %s",
1264 nfs_strerror(status.nfsv2.fhs_status));
1267 memcpy(data.root.data,
1268 (char *) status.nfsv2.fhstatus_u.fhs_fhandle,
1270 data.root.size = NFS_FHSIZE;
1271 memcpy(data.old_root.data,
1272 (char *) status.nfsv2.fhstatus_u.fhs_fhandle,
1275 fhandle3 *my_fhandle;
1276 if (status.nfsv3.fhs_status != 0) {
1277 bb_error_msg("%s:%s failed, reason given by server: %s",
1279 nfs_strerror(status.nfsv3.fhs_status));
1282 my_fhandle = &status.nfsv3.mountres3_u.mountinfo.fhandle;
1283 memset(data.old_root.data, 0, NFS_FHSIZE);
1284 memset(&data.root, 0, sizeof(data.root));
1285 data.root.size = my_fhandle->fhandle3_len;
1286 memcpy(data.root.data,
1287 (char *) my_fhandle->fhandle3_val,
1288 my_fhandle->fhandle3_len);
1290 data.flags |= NFS_MOUNT_VER3;
1293 /* create nfs socket for kernel */
1296 if (nfs_mount_version < 3) {
1297 bb_error_msg("NFS over TCP is not supported");
1300 fsock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1302 fsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1304 bb_perror_msg("nfs socket");
1307 if (bindresvport(fsock, 0) < 0) {
1308 bb_perror_msg("nfs bindresvport");
1312 server_addr.sin_port = PMAPPORT;
1313 port = pmap_getport(&server_addr, nfsprog, nfsvers,
1314 tcp ? IPPROTO_TCP : IPPROTO_UDP);
1318 server_addr.sin_port = htons(port);
1320 /* prepare data structure for kernel */
1323 memcpy((char *) &data.addr, (char *) &server_addr, sizeof(data.addr));
1324 strncpy(data.hostname, hostname, sizeof(data.hostname));
1328 auth_destroy(mclient->cl_auth);
1329 clnt_destroy(mclient);
1334 /* We must wait until mount directory is available */
1335 struct stat statbuf;
1337 while (stat(mp->mnt_dir, &statbuf) == -1) {
1339 daemonized = daemonize();
1340 if (daemonized <= 0) { /* parent or error */
1341 // FIXME: parent doesn't close fsock - ??!
1342 retval = -daemonized;
1346 sleep(delay); /* 1, 2, 4, 8, 16, 30, ... */
1353 do_mount: /* perform actual mount */
1355 mp->mnt_type = (char*)"nfs";
1356 retval = mount_it_now(mp, vfsflags, (char*)&data);
1363 auth_destroy(mclient->cl_auth);
1364 clnt_destroy(mclient);
1378 #else /* !ENABLE_FEATURE_MOUNT_NFS */
1380 /* Never called. Call should be optimized out. */
1381 int nfsmount(struct mntent *mp, int vfsflags, char *filteropts);
1383 #endif /* !ENABLE_FEATURE_MOUNT_NFS */
1385 // Mount one directory. Handles CIFS, NFS, loopback, autobind, and filesystem
1386 // type detection. Returns 0 for success, nonzero for failure.
1387 // NB: mp->xxx fields may be trashed on exit
1388 static int singlemount(struct mntent *mp, int ignore_busy)
1390 int rc = -1, vfsflags;
1391 char *loopFile = 0, *filteropts = 0;
1395 vfsflags = parse_mount_options(mp->mnt_opts, &filteropts);
1397 // Treat fstype "auto" as unspecified.
1399 if (mp->mnt_type && strcmp(mp->mnt_type,"auto") == 0)
1402 // Might this be an CIFS filesystem?
1404 if (ENABLE_FEATURE_MOUNT_CIFS
1405 && (!mp->mnt_type || strcmp(mp->mnt_type,"cifs") == 0)
1406 && (mp->mnt_fsname[0]=='/' || mp->mnt_fsname[0]=='\\')
1407 && mp->mnt_fsname[0]==mp->mnt_fsname[1]
1409 len_and_sockaddr *lsa;
1414 // Replace '/' with '\' and verify that unc points to "//server/share".
1416 for (s = mp->mnt_fsname; *s; ++s)
1417 if (*s == '/') *s = '\\';
1421 s = strrchr(mp->mnt_fsname, '\\');
1422 if (s <= mp->mnt_fsname+1) goto report_error;
1424 lsa = host2sockaddr(mp->mnt_fsname+2, 0);
1426 if (!lsa) goto report_error;
1428 // insert ip=... option into string flags.
1430 dotted = xmalloc_sockaddr2dotted_noport(&lsa->sa);
1431 ip = xasprintf("ip=%s", dotted);
1432 parse_mount_options(ip, &filteropts);
1434 // compose new unc '\\server-ip\share'
1435 // (s => slash after hostname)
1437 mp->mnt_fsname = xasprintf("\\\\%s%s", dotted, s);
1440 vfsflags |= MS_MANDLOCK;
1442 mp->mnt_type = (char*)"cifs";
1443 rc = mount_it_now(mp, vfsflags, filteropts);
1444 if (ENABLE_FEATURE_CLEAN_UP) {
1445 free(mp->mnt_fsname);
1453 // Might this be an NFS filesystem?
1455 if (ENABLE_FEATURE_MOUNT_NFS
1456 && (!mp->mnt_type || !strcmp(mp->mnt_type, "nfs"))
1457 && strchr(mp->mnt_fsname, ':') != NULL
1459 rc = nfsmount(mp, vfsflags, filteropts);
1463 // Look at the file. (Not found isn't a failure for remount, or for
1464 // a synthetic filesystem like proc or sysfs.)
1465 // (We use stat, not lstat, in order to allow
1466 // mount symlink_to_file_or_blkdev dir)
1468 if (!stat(mp->mnt_fsname, &st)
1469 && !(vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE))
1471 // Do we need to allocate a loopback device for it?
1473 if (ENABLE_FEATURE_MOUNT_LOOP && S_ISREG(st.st_mode)) {
1474 loopFile = bb_simplify_path(mp->mnt_fsname);
1475 mp->mnt_fsname = NULL; /* will receive malloced loop dev name */
1476 if (set_loop(&(mp->mnt_fsname), loopFile, 0) < 0) {
1477 if (errno == EPERM || errno == EACCES)
1478 bb_error_msg(bb_msg_perm_denied_are_you_root);
1480 bb_perror_msg("cannot setup loop device");
1484 // Autodetect bind mounts
1486 } else if (S_ISDIR(st.st_mode) && !mp->mnt_type)
1487 vfsflags |= MS_BIND;
1490 /* If we know the fstype (or don't need to), jump straight
1491 * to the actual mount. */
1493 if (mp->mnt_type || (vfsflags & (MS_REMOUNT | MS_BIND | MS_MOVE)))
1494 rc = mount_it_now(mp, vfsflags, filteropts);
1496 // Loop through filesystem types until mount succeeds
1499 /* Initialize list of block backed filesystems. This has to be
1500 * done here so that during "mount -a", mounts after /proc shows up
1501 * can autodetect. */
1504 fslist = get_block_backed_filesystems();
1505 if (ENABLE_FEATURE_CLEAN_UP && fslist)
1506 atexit(delete_block_backed_filesystems);
1509 for (fl = fslist; fl; fl = fl->link) {
1510 mp->mnt_type = fl->data;
1511 rc = mount_it_now(mp, vfsflags, filteropts);
1516 // If mount failed, clean up loop file (if any).
1518 if (ENABLE_FEATURE_MOUNT_LOOP && rc && loopFile) {
1519 del_loop(mp->mnt_fsname);
1520 if (ENABLE_FEATURE_CLEAN_UP) {
1522 free(mp->mnt_fsname);
1527 if (ENABLE_FEATURE_CLEAN_UP)
1530 if (errno == EBUSY && ignore_busy)
1533 bb_perror_msg("mounting %s on %s failed", mp->mnt_fsname, mp->mnt_dir);
1537 // Parse options, if necessary parse fstab/mtab, and call singlemount for
1538 // each directory to be mounted.
1540 static const char must_be_root[] ALIGN1 = "you must be root";
1542 int mount_main(int argc, char **argv);
1543 int mount_main(int argc, char **argv)
1545 enum { OPT_ALL = 0x10 };
1547 char *cmdopts = xstrdup(""), *fstype=0, *storage_path=0;
1549 const char *fstabname;
1553 struct mntent mtpair[2], *mtcur = mtpair;
1554 SKIP_DESKTOP(const int nonroot = 0;)
1555 USE_DESKTOP( int nonroot = (getuid() != 0);)
1557 /* parse long options, like --bind and --move. Note that -o option
1558 * and --option are synonymous. Yes, this means --remount,rw works. */
1560 for (i = j = 0; i < argc; i++) {
1561 if (argv[i][0] == '-' && argv[i][1] == '-') {
1562 append_mount_options(&cmdopts, argv[i]+2);
1563 } else argv[j++] = argv[i];
1568 // Parse remaining options
1570 opt = getopt32(argv, "o:t:rwanfvsi", &opt_o, &fstype);
1571 if (opt & 0x1) append_mount_options(&cmdopts, opt_o); // -o
1572 //if (opt & 0x2) // -t
1573 if (opt & 0x4) append_mount_options(&cmdopts, "ro"); // -r
1574 if (opt & 0x8) append_mount_options(&cmdopts, "rw"); // -w
1575 //if (opt & 0x10) // -a
1576 if (opt & 0x20) USE_FEATURE_MTAB_SUPPORT(useMtab = 0); // -n
1577 if (opt & 0x40) USE_FEATURE_MTAB_SUPPORT(fakeIt = 1); // -f
1578 //if (opt & 0x80) // -v: verbose (ignore)
1579 //if (opt & 0x100) // -s: sloppy (ignore)
1580 //if (opt & 0x200) // -i: don't call mount.<fstype> (ignore)
1584 // Three or more non-option arguments? Die with a usage message.
1586 if (argc > 2) bb_show_usage();
1588 // If we have no arguments, show currently mounted filesystems
1591 if (!(opt & OPT_ALL)) {
1592 FILE *mountTable = setmntent(bb_path_mtab_file, "r");
1594 if (!mountTable) bb_error_msg_and_die("no %s", bb_path_mtab_file);
1596 while (getmntent_r(mountTable, mtpair, bb_common_bufsiz1,
1597 sizeof(bb_common_bufsiz1)))
1599 // Don't show rootfs. FIXME: why??
1600 // util-linux 2.12a happily shows rootfs...
1601 //if (!strcmp(mtpair->mnt_fsname, "rootfs")) continue;
1603 if (!fstype || !strcmp(mtpair->mnt_type, fstype))
1604 printf("%s on %s type %s (%s)\n", mtpair->mnt_fsname,
1605 mtpair->mnt_dir, mtpair->mnt_type,
1608 if (ENABLE_FEATURE_CLEAN_UP) endmntent(mountTable);
1609 return EXIT_SUCCESS;
1611 } else storage_path = bb_simplify_path(argv[0]);
1613 // When we have two arguments, the second is the directory and we can
1614 // skip looking at fstab entirely. We can always abspath() the directory
1615 // argument when we get it.
1619 bb_error_msg_and_die(must_be_root);
1620 mtpair->mnt_fsname = argv[0];
1621 mtpair->mnt_dir = argv[1];
1622 mtpair->mnt_type = fstype;
1623 mtpair->mnt_opts = cmdopts;
1624 rc = singlemount(mtpair, 0);
1628 i = parse_mount_options(cmdopts, 0);
1629 if (nonroot && (i & ~MS_SILENT)) // Non-root users cannot specify flags
1630 bb_error_msg_and_die(must_be_root);
1632 // If we have a shared subtree flag, don't worry about fstab or mtab.
1634 if (ENABLE_FEATURE_MOUNT_FLAGS
1635 && (i & (MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE))
1637 rc = mount("", argv[0], "", i, "");
1638 if (rc) bb_perror_msg_and_die("%s", argv[0]);
1642 // Open either fstab or mtab
1644 fstabname = "/etc/fstab";
1645 if (i & MS_REMOUNT) {
1646 fstabname = bb_path_mtab_file;
1648 fstab = setmntent(fstabname, "r");
1650 bb_perror_msg_and_die("cannot read %s", fstabname);
1652 // Loop through entries until we find what we're looking for.
1654 memset(mtpair, 0, sizeof(mtpair));
1656 struct mntent *mtnext = (mtcur==mtpair ? mtpair+1 : mtpair);
1658 // Get next fstab entry
1660 if (!getmntent_r(fstab, mtcur, bb_common_bufsiz1
1661 + (mtcur==mtpair ? sizeof(bb_common_bufsiz1)/2 : 0),
1662 sizeof(bb_common_bufsiz1)/2))
1664 // Were we looking for something specific?
1668 // If we didn't find anything, complain.
1670 if (!mtnext->mnt_fsname)
1671 bb_error_msg_and_die("can't find %s in %s",
1672 argv[0], fstabname);
1676 // fstab must have "users" or "user"
1677 if (!(parse_mount_options(mtcur->mnt_opts, 0) & MOUNT_USERS))
1678 bb_error_msg_and_die(must_be_root);
1681 // Mount the last thing we found.
1683 mtcur->mnt_opts = xstrdup(mtcur->mnt_opts);
1684 append_mount_options(&(mtcur->mnt_opts), cmdopts);
1685 rc = singlemount(mtcur, 0);
1686 free(mtcur->mnt_opts);
1691 /* If we're trying to mount something specific and this isn't it,
1692 * skip it. Note we must match both the exact text in fstab (ala
1693 * "proc") or a full path from root */
1697 // Is this what we're looking for?
1699 if (strcmp(argv[0], mtcur->mnt_fsname) &&
1700 strcmp(storage_path, mtcur->mnt_fsname) &&
1701 strcmp(argv[0], mtcur->mnt_dir) &&
1702 strcmp(storage_path, mtcur->mnt_dir)) continue;
1704 // Remember this entry. Something later may have overmounted
1705 // it, and we want the _last_ match.
1709 // If we're mounting all.
1712 // Do we need to match a filesystem type?
1713 if (fstype && match_fstype(mtcur, fstype)) continue;
1715 // Skip noauto and swap anyway.
1717 if (parse_mount_options(mtcur->mnt_opts, 0)
1718 & (MOUNT_NOAUTO | MOUNT_SWAP)) continue;
1720 // No, mount -a won't mount anything,
1721 // even user mounts, for mere humans.
1724 bb_error_msg_and_die(must_be_root);
1726 // Mount this thing.
1728 // NFS mounts want this to be xrealloc-able
1729 mtcur->mnt_opts = xstrdup(mtcur->mnt_opts);
1730 if (singlemount(mtcur, 1)) {
1731 /* Count number of failed mounts */
1734 free(mtcur->mnt_opts);
1737 if (ENABLE_FEATURE_CLEAN_UP) endmntent(fstab);
1741 if (ENABLE_FEATURE_CLEAN_UP) {